Search code examples
timerluadelayed-execution

Sleeping in Lua Without Prohibiting Previous Command


In Lua there is no simple way to sleep for a desired amount of time. To fix this I created a function that does this for me:

local clock = os.clock
function sleep(n)  -- seconds
   local t0 = clock()
   while clock() - t0 <= n do
   end
end

I then applied it to some code:

player:applyLinearImpulse(0, -14, player.x, player.y)
sleep(1)

The goal was to apply a linear impulse to the ground then freeze the game. However, this simply freezes the game before applying the impulse. In general how can I make sure the previous command is carried out before I sleep?


Solution

  • In Corona, dynamic actions on objects (like applying an impulse, moving, starting a timer, etc) are really only "enacted" after your code returns. You would have to use timer.performWithDelay(1, function() sleep(1) end).

    Once the timer callback is run, the GUI will only be updated upon return from that callback (sleep), so your GUI will be frozen during 1 second. That seems to be the effect you are looking for, though usually you don't want to freeze the GUI.