The API document shows two methods to pass parameter to event handler, the closure method and variable handld method (http://docs.coronalabs.com/api/library/timer/performWithDelay.html).
I have some background in functional language so I prefer the closure method, but there is a lot of typing there. I think the better and cleaner way to do is to use a trick called Curry function.
Curry function basically transforms a function with n parameters to a new function with n-1 parameters. Lua-users.org has good explanation and examples but they are quite generic. Since we want it for passing parameter to event handler, we can be a bit more specific here.
So, we define the currying function like this (you only need to define it once within scope)
function curry1(f, v) return function (y) return f(v,y) end end
Then we define our event handler with extra parameter
function handler(v, event) print(v) end
‘v’ is the parameter we will pass our custom value onto. ‘event’ will be populated by event dispatcher as usual.
We can use it in the dispatcher like this:
timer.performWithDelay(1000, curry1(handler, 10))
In this case, 10 will be passed to the handler function. As you can see, we can save a lot of typing using curry, and it looks a lot cleaner too.
Here’s main.lua that you can copy-and-paste to play with.
function curry1(f, v) return function (y) return f(v,y) end end function handler(v, event) print(v) end function handler2(t, event) print(t.a) print(t.b) end timer.performWithDelay(1000, curry1(handler, 10)) timer.performWithDelay(2000, curry1(handler2, {a=1, b=2}))
Note that I wrote about this on my blog if you are interested.
Hope you guys find it useful in your projects. Happy coding!