Help understanding Closures.

I'm trying to setup an animation for when my level boss dies.

I want to have a series of explosions, starting small, building up to larger ones that randomly appear around the boss and terminating with a big explosion where the boss was.

Here's a chunk of my code in question:

1
2
3
4
5
6
7
8
    for i = 1, 10 do
        dx = math.random(60) - 30 + x
        dy = math.random(60) - 30 + y
        t = math.random(2000)
        print("dx = " .. dx .. " dy = " .. dy)
        local myBoomClosure = function() return newExplosion(dx, dy, "bang") end
        timer.performWithDelay(t,myBoomClosure)
    end

The values of dx and dy that get passed to newExplosion aren't the values when you first set the timer, it's the values when the function is called. At that point dx and dy aren't changing value anymore, they are a static value throughout all calls to the function.

You shouldn't be figuring out those random values ahead of time, you should be finding the values in the function that gets called.

Thats what I suspected. I was hoping that it would capture the dx and dy values as it looped. Two new intermediate functions later, my boss blows up nicely.

Thanks!

views:1307 update:2011/10/3 8:06:12
corona forums © 2003-2011