]> git.lizzy.rs Git - lua_async.git/blob - timeouts.lua
Merge branch 'master' of https://github.com/EliasFleckenstein03/lua_async
[lua_async.git] / timeouts.lua
1 local unpack = unpack or table.unpack
2 lua_async.timeouts = {
3         pool = {},
4         executing = {},
5         last_id = 0,
6 }
7
8 function setTimeout(callback, ms, ...)
9         local id = lua_async.timeouts.last_id + 1
10         lua_async.timeouts.last_id = id
11         lua_async.timeouts.pool[id] = {
12                 time_left = (ms or 0) / 1000,
13                 callback = callback,
14                 args = {...},
15         }
16         return id
17 end
18
19 function clearTimeout(id)
20         lua_async.timeouts.pool[id] = nil
21         lua_async.timeouts.executing[id] = nil
22 end
23
24 function lua_async.timeouts.step(dtime)
25         lua_async.timeouts.executing = lua_async.timeouts.pool
26         lua_async.timeouts.pool = {}
27
28         for id, timeout in pairs(lua_async.timeouts.executing) do
29                 timeout.time_left = timeout.time_left - dtime
30
31                 if timeout.time_left <= 0 then
32                         timeout.callback(unpack(timeout.args))
33                 else
34                         lua_async.timeouts.pool[id] = timeout
35                 end
36
37                 lua_async.timeouts.executing[id] = nil
38         end
39 end