From a2770298f040307f8dd59c7a88d7e40d37faec14 Mon Sep 17 00:00:00 2001 From: Elias Fleckenstein Date: Fri, 6 Aug 2021 19:19:23 +0200 Subject: Add source code --- timeouts.lua | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 timeouts.lua (limited to 'timeouts.lua') diff --git a/timeouts.lua b/timeouts.lua new file mode 100644 index 0000000..b3b69e8 --- /dev/null +++ b/timeouts.lua @@ -0,0 +1,30 @@ +lua_async.timeouts = { + pool = {}, + last_id = 0, +} + +function setTimeout(callback, ms, ...) + local id = lua_async.timeouts.last_id + 1 + lua_async.timeouts.last_id = id + lua_async.timeouts.pool[id] = { + time_left = (ms or 0) / 1000, + callback = callback, + args = {...}, + } + return id +end + +function clearTimeout(id) + lua_async.timeouts.pool[id] = nil +end + +function lua_async.timeouts.step(dtime) + for id, timeout in pairs(lua_async.timeouts.pool) do + timeout.time_left = timeout.time_left - dtime + + if timeout.time_left <= 0 then + timeout.callback(unpack(timeout.args)) + clearTimeout(id) + end + end +end -- cgit v1.2.3