Does Moai support an API like ‘setTimeout’?
http://getmoai.com/forums/moai-sdk-developer-support/does-moai-support-an-api-like-settimeout/
Me
Hi,
Does Moai support an API like JavaScript’s setTimeout, which schedules a function execution after a specified time. I noticed there is a Moai class called MOAITimer, so I’m wondering if this class could be used for this purpose? I know a ‘setTimeout’ function could be easily realized on Lua level using MOAISim:getElapsedTime() and Lua’s ‘pcall’ function, but I’m just lazy and wonder if there is a shortcut that Moai has provided?
Thank you~
Josh
Moai doesn’t support that, but for convenience I’ll share the Lua function I use for this exact purpose:
(Hide some code)
EDIT: updated while investigating bug mentioned below. Will ensure this code works once bug is fixed.
Me
Thank you for the sharing, but the function gives the following error after I run:
cannot use ‘…’ outside a vararg function near ‘…’
I think ‘…’ are also needed for “function()” in the 5th line, so I added it.
However, after I ran the following code
function printAStr( str ) print( str ) end callWithDelay( 1, printAStr, "helloWorld" )
It prints “userdata: 0x3192c4” instead of “helloWorld”, any clue for this? I think the core issue is how to pass arguments to the callback function of timer’s listener?
Josh
I made two mistakes in my function, which I have corrected above. You are correct I forgot to pass the … properly, and I also forgot that the timer listener callback receives the timer as the first parameter, which is why you were seeing the userdata print out in your test.
Me
seems still unworkable for the arguments pass…
Ok, so my question is how to pass arguments to callback function of timer’s listener?
Josh
It looks like there may be a bug in the listener with the last release. I’ve opened a bug on the issue. I also realized yet another error in my above code, and have corrected it. Hopefully that’s the last edit I have to do. 🙂
Patrick
Thanks for finding the bug. Won’t be able to get to it for a day or so. Sorry for the trouble!
Patrick
OK, finally had time to look at this. It looks like it’s working correctly. The code I used is below.
MOAISim.openWindow ( "test", 320, 480 ) function callWithDelay ( delay, func, ... ) local timer = MOAITimer.new () timer:setSpan ( delay ) timer:setListener ( MOAITimer.EVENT_TIMER_LOOP, function () timer:stop () timer = nil func ( unpack ( arg )) end ) timer:start () end function printAStr ( str ) print( str ) end callWithDelay ( 1, printAStr, "helloWorld" )
Me
It works! Thanks a lot 🙂
Recent Comments