]> git.lizzy.rs Git - lua_async.git/blob - timeouts.lua
Add source code
[lua_async.git] / timeouts.lua
1 lua_async.timeouts = {
2         pool = {},
3         last_id = 0,
4 }
5
6 function setTimeout(callback, ms, ...)
7         local id = lua_async.timeouts.last_id + 1
8         lua_async.timeouts.last_id = id
9         lua_async.timeouts.pool[id] = {
10                 time_left = (ms or 0) / 1000,
11                 callback = callback,
12                 args = {...},
13         }
14         return id
15 end
16
17 function clearTimeout(id)
18         lua_async.timeouts.pool[id] = nil
19 end
20
21 function lua_async.timeouts.step(dtime)
22         for id, timeout in pairs(lua_async.timeouts.pool) do
23                 timeout.time_left = timeout.time_left - dtime
24
25                 if timeout.time_left <= 0 then
26                         timeout.callback(unpack(timeout.args))
27                         clearTimeout(id)
28                 end
29         end
30 end