This might seem like a stupid question, but can I send function arguments from within a Corona timer?
For example, here's a completely basic function call on timer:
timer.performWithDelay( 1000, restartLevel )
If possible, I would like to send one or more arguments to the function "restartLevel". Maybe it would look something like this (but probably not).
1 2 | timer.performWithDelay( 1000, restartLevel( true, "resetScore" ) ) -- the 'true' and "resetScore" are just example arguments, sent to "restartLevel" |
Here you go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | timer.oldPerformWithDelay = timer.performWithDelay local function restartLevel(params) print("param1", params[1]) print("param2", params[2]) end timer.performWithDelay = function(interval, func, ...) local params = {...} local function doIt() func(params) end timer.oldPerformWithDelay(interval, doIt) end timer.performWithDelay(1000, restartLevel, true, "yo") |
After a little more thought, I made this more robust, and added support for multiple iterations, which I completely forgot about when I first replied. You can see the end result here:
http://www.ludicroussoftware.com/blog/2011/09/05/passing-parameters-in-a-timer/
Thanks,
Darren
Darren, that's a brilliant example of one of the cool things you can do in Lua. You can take any existing function and basically "rewrite" it!
Another way to send parameters would be to use an anonymous function for the callback instead of just naming a function.
1 2 3 4 5 6 7 | local function restartLevel(t, r) print(t, r) end timer.performWithDelay(1000, function() restartLevel(true, "resetScore") end) |
Hey Gilbert!
Yeah, that's another route, which is basically the same as using a closure, but it looks messier to me when I'm reading code. I like the structure of putting the function into a local variable, just for the sake of formatting.
Hope you're well!
Darren
Thank you immensely Darren and Gilbert!
These two solutions are definitely superior to my "workarounds" of nesting functions or setting local "flag" variables to represent the function arguments I need. I'm going to tinker around with each method to see which works best for my purposes.
Brent Sorrentino
Ignis Design