]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/common/after.lua
e20f292f0240ab69e83e0369c1ae1f29fe775354
[dragonfireclient.git] / builtin / common / after.lua
1 local jobs = {}
2 local time = 0.0
3 local time_next = math.huge
4
5 core.register_globalstep(function(dtime)
6         time = time + dtime
7
8         if time < time_next then
9                 return
10         end
11
12         time_next = math.huge
13
14         -- Iterate backwards so that we miss any new timers added by
15         -- a timer callback.
16         for i = #jobs, 1, -1 do
17                 local job = jobs[i]
18                 if time >= job.expire then
19                         core.set_last_run_mod(job.mod_origin)
20                         job.func(unpack(job.arg))
21                         local jobs_l = #jobs
22                         jobs[i] = jobs[jobs_l]
23                         jobs[jobs_l] = nil
24                 elseif job.expire < time_next then
25                         time_next = job.expire
26                 end
27         end
28 end)
29
30 function core.after(after, func, ...)
31         assert(tonumber(after) and type(func) == "function",
32                 "Invalid minetest.after invocation")
33         local expire = time + after
34         local new_job = {
35                 func = func,
36                 expire = expire,
37                 arg = {...},
38                 mod_origin = core.get_last_run_mod(),
39         }
40         jobs[#jobs + 1] = new_job
41         time_next = math.min(time_next, expire)
42         return { cancel = function() new_job.func = function() end end }
43 end