Game Development Reference
In-Depth Information
co = coroutine.create(showProgress)
while coroutine.status(co) ~= "dead" do
_,res = coroutine.resume(co)
if res/tStep == math.floor(res/tStep) then print(res/tStep .. " % done") end
end
The facility to resume midway and pass the function new parameters can be very useful when
dealing with functions that rely on updated data. We shall not look at a complex example, but to
illustrate the point, here's a simple one:
a = 100
co = coroutine.create(function()
print( "we start at ", a)
a = coroutine.yield(a)
print("We restart this function with the value of ", a)
end)
_, res = coroutine.resume(co)
print("We stopped or yielded at", res)
_,res = coroutine.resume(co, 200)
Game Loops
A game in the simplest of terms is a repeating loop that takes inputs and updates the screen and
characters. So in terms of pseudocode, a game might look like this:
while playing do
getInput()
updateCharacters()
updateScreen()
end
In this case, getInput() is a function that would get some form of input from the player, either from
the keyboard or via touch. updateCharacters() is the function that would update the game play
elements, the characters on the screen, and the board. Lastly, updateScreen() would update the
score, the lives, the messages, and so on. If this were written in C, C++, or similar, this would be fine,
but in Lua, the while loops are not very stable. Coroutines come in handy to make these routines
more responsive.
Another interesting thing is that although coroutines in Lua are not threads, they can be used like
threads (i.e., you can define multiple coroutines). Here's an example:
c1 = coroutine.create(function()
for i=1,20 do
print( "function 1: ", i)
end
end)
c2 = coroutine.create(function()
for i=1,5 do
print( "function 2: ", i)
end
end)
 
Search WWH ::




Custom Search