Game Development Reference
In-Depth Information
Progress Bars
Another practical example for using coroutines is with progress bars, as in the following example:
function doLongProcessing(a)
-- Do something
thread1 = coroutine.yield("25%")
-- Do something
thread1 = coroutine.yield("50%")
-- Do something
thread1 = coroutine.yield("75%")
-- Do something
return "100%"
local _, res = coroutine.resume(thread)
print( "Progress is now " .. res )
tStep = 1000
for i=1,100000 do
if i/tStep == math.floor(i/tStep) then print( i/tStep .. " % done")
end
When run in the Lua terminal, this code is responsive, but when run on some frameworks, this can
be very unstable, as it can choke the CPU while running the loop (similar to the application freezing).
This is a very good example of where coroutines can help.
We have a coroutine function that runs the code from 1 to 100,000. Every time this coroutine is
called, it iterates to the next number and yields. We set up another loop that keeps calling this code
till the coroutine status is dead , and when the iteration number is a multiple of 1,000, we print out the
progress as the percentage done.
tStep = 1000
function showProgress()
for i=1,100000 do
coroutine.yield(i)
end
end
We have the body of our function; now we need to have a loop that will work on this.
 
Search WWH ::




Custom Search