I really should do a blog post on this topic.
Traditionally games use something called a “game loop” that constantly watches for input from the devices (including the network for multi-player games).
Under Corona SDK’s hood, there most likely is such a loop that manages all the animations and screen updates as well as monitors for touch events and network input.
While Lua supports FOR and WHILE loops where you could write your own, the problem with that is that there is no way to keep your loop from eating up all the CPU time. If this were Objective C there are controls that sleep your app except when it needs to run. So if you tried a
while true do
some stuff
end
your app would be very very slow because that loop would be eating up CPU time.
The solution to this is to understand that Corona SDK is an Event generation engine. You setup listeners to listen for events to happen like input and you just have to react to that.
Well how do you do something continuously then? Well you have an event listener that listens for an event called “enterFrame”. This event fires off 30 times per second on a 30FPS game, or 60 times per second on a 60FPS game. This is Corona’s game loop running. It does any transitions, timers and physics, updates the graphics and redraws the screen. During that loop, it goes "Well the developer might need to do something, let me call their event listener(s … you can have multiple!) and do the work they need to do while I’m looping for them.
So I typically create a function that I call gameLoop()
local function gameLoop()
what I want to happen continiouslly like moving stuff, checking for
collisions, spawning new enemies, etc.
end
Runtime:addEventListener("enterFrame", gameLoop)
Now every 1/30th (or 1/60th) of a second, gameLoop will execute and you can spawn critters to your heart’s content.
[import]uid: 19626 topic_id: 14174 reply_id: 54870[/import]