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:

 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  

X and y are passed to the function that contains the above code. Variable i is declared locally higher up in the function.

This is the first block that creates 10 small explosions at random points. A 2nd block creates 5 bigger explosions. Finally I call newExplosion(x,y,“jumbo”) to play the biggest explosion over top of the boss.

The problem is that newExplosion() gets the same x and y on each call.

Apparently I don’t understand closuers well.

Can someone straighten me out? Is there a better way to pass parameters into the timer callBack?

Thanks
Rob
[import]uid: 19626 topic_id: 9318 reply_id: 309318[/import]

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. [import]uid: 12108 topic_id: 9318 reply_id: 34017[/import]

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!
[import]uid: 19626 topic_id: 9318 reply_id: 34025[/import]