diff options
author | Guillermo Ramos | 2014-07-01 20:51:07 +0200 |
---|---|---|
committer | Guillermo Ramos | 2014-07-01 20:51:07 +0200 |
commit | f3c354d396a38033dac28ece6f6220e75cef5aec (patch) | |
tree | 98c0977e8152472463cd2947589f725c9d5e2551 /lua/scheduler.lua | |
parent | aef238a0600c5cb775bb371dbb2463fd0381bff9 (diff) | |
download | 7l-f3c354d396a38033dac28ece6f6220e75cef5aec.tar.gz |
[Lua] Día 2 (sin terminar)
Diffstat (limited to 'lua/scheduler.lua')
-rw-r--r-- | lua/scheduler.lua | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/lua/scheduler.lua b/lua/scheduler.lua new file mode 100644 index 0000000..e526efa --- /dev/null +++ b/lua/scheduler.lua @@ -0,0 +1,39 @@ +pending = {} + +function schedule(time, action) + pending[#pending+1] = { + time = time, + action = action + } + + sort_by_time(pending) +end + +function sort_by_time(array) + table.sort(array, function(e1, e2) return e1.time < e2.time end) +end + +function wait(seconds) + coroutine.yield(seconds) +end + +function run() + while #pending > 0 do + while os.clock() < pending[1].time do end -- busy-wait + + local item = remove_first(pending) + local _, seconds = coroutine.resume(item.action) + + if seconds then + later = os.clock() + seconds + schedule(later, item.action) + end + end +end + +function remove_first(array) + result = array[1] + array[1] = array[#array] + array[#array] = nil + return result +end |