Last active
August 29, 2015 14:21
-
-
Save scambier/25a78681a0b4dd1af1fe to your computer and use it in GitHub Desktop.
waitForSeconds Lua function equivalent to "new WaitForSeconds()" from Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- 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