For examples, I’d suggest something fairly linear but which would normally get snarled in callbacks or become a heavy state machine. Game loops and character AI are fairly fertile ground, here.
You can get pretty far by building around a few specialized wait routines, e.g. for time, something like
[lua]local function WaitMS (ms, update_func)
local ends_at = system.getTimer() + ms
while system.getTimer() < ends_at do
if update_func then
update_func()
end
coroutine.yield()
end
end
– Toy example
timer.performWithDelay(100, coroutine.wrap(function(event)
print(“Start”)
WaitMS(4000, function() print(“Waiting…”) end)
print(“Done!”)
WaitMS(1500)
WaitMS(2000, function() print(“Waiting a little more…”) end)
print(“Done for real.”)
timer.cancel(event.source)
end), 0)[/lua]
Other possibilities include “wait for table field to be true / false”, “wait for function to return true / false”, “wait for transition”, etc.
In one of my snippets I use a coroutine to take a peek at a big long iterative process (incrementally generating a Hilbert curve) and draw it as it goes along:
Hilbert code
Timer code (mostly the same wrap() + performWithDelay() from above
The sample itself
[import]uid: 27791 topic_id: 33476 reply_id: 133886[/import]