Skip to content

Instantly share code, notes, and snippets.

@wilbefast
Last active August 29, 2015 14:19
Show Gist options
  • Save wilbefast/0a1dcd4e8ffd69b03bad to your computer and use it in GitHub Desktop.
Save wilbefast/0a1dcd4e8ffd69b03bad to your computer and use it in GitHub Desktop.
Coroutines in Lua
local _coroutines = {}
local _add = function(c)
-- add a new coroutine to be "babysat"
table.insert(_coroutines, c)
end
local _clear = function()
-- remove all the coroutines, start afresh
_coroutines = {}
end
local _countRunning = function()
return #_coroutines
end
local _update = function(dt)
-- this is where I'd really love J. Blow's 'remove' primitive...
local i = 1
while i <= #_coroutines do
local c = _coroutines[i]
-- this passes delta-time to the coroutine using Lua magic
coroutine.resume(c, dt)
-- remove any couroutines that have finished
if coroutine.status(c) == "dead" then
table.remove(_coroutines, i)
else
i = i + 1
end
end
end
return {
add = _add,
update = _update,
clear = _clear,
countRunning = _countRunning
}
require("babysitter")
function love.keypressed(key, uni)
-- patience is a virtue ...
if babysitter.countRunning() > 0 then
return
end
-- wait for one second then exit
babysitter.add(coroutine.create(function(dt)
local t = 0
while t < 1 do
-- timer counts up to 1 second in total
t = t + dt
-- we can also fade out the music very nicely here
music:setVolume(1 - t)
-- resume here next update
coroutine.yield()
end
love.event.push("quit")
end))
end
function love.update(dt)
babysitter.update(dt)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment