]> git.lizzy.rs Git - minetest.git/blob - builtin/common/after.lua
[CSM] sound_play & sound_stop support + client_lua_api doc (#5096)
[minetest.git] / builtin / common / after.lua
1 local jobs = {}
2 local time = 0.0
3 local last = core.get_us_time() / 1000000
4
5 core.register_globalstep(function(dtime)
6         local new = core.get_us_time() / 1000000
7         if new > last then
8                 time = time + (new - last)
9         else
10                 -- Overflow, we may lose a little bit of time here but
11                 -- only 1 tick max, potentially running timers slightly
12                 -- too early.
13                 time = time + new
14         end
15         last = new
16
17         if #jobs < 1 then
18                 return
19         end
20
21         -- Iterate backwards so that we miss any new timers added by
22         -- a timer callback, and so that we don't skip the next timer
23         -- in the list if we remove one.
24         for i = #jobs, 1, -1 do
25                 local job = jobs[i]
26                 if time >= job.expire then
27                         core.set_last_run_mod(job.mod_origin)
28                         job.func(unpack(job.arg))
29                         table.remove(jobs, i)
30                 end
31         end
32 end)
33
34 function core.after(after, func, ...)
35         assert(tonumber(after) and type(func) == "function",
36                 "Invalid core.after invocation")
37         jobs[#jobs + 1] = {
38                 func = func,
39                 expire = time + after,
40                 arg = {...},
41                 mod_origin = core.get_last_run_mod()
42         }
43 end