Skip to content

Instantly share code, notes, and snippets.

@scambier
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save scambier/25a78681a0b4dd1af1fe to your computer and use it in GitHub Desktop.

Select an option

Save scambier/25a78681a0b4dd1af1fe to your computer and use it in GitHub Desktop.
waitForSeconds Lua function equivalent to "new WaitForSeconds()" from Unity
-- Heavily inspired by http://www.mohiji.org/2012/12/14/lua-coroutines/
require 'socket'
local WAITING_COROUTINES = {}
function waitForSeconds(seconds)
local milli = seconds * 1000
local co = coroutine.running()
assert(co ~= nil, "Cannot wait on main thread")
local wakeuptime = socket.gettime() * 1000 + milli
WAITING_COROUTINES[co] = wakeuptime
return coroutine.yield(co)
end
function wakeupWaitingCoroutines()
local toWake = {}
for co, wakeuptime in pairs(WAITING_COROUTINES) do
if wakeuptime < socket.gettime() * 1000 then
table.insert(toWake, co)
end
end
for _, co in ipairs(toWake) do
WAITING_COROUTINES[co] = nil
coroutine.resume(co)
end
end
-- Usage example
local co = coroutine.create(function()
repeatEach()
end)
coroutine.resume(co)
function repeatEach()
while true do
print("tick")
waitForSeconds(1)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment