2017-01-22 11:17:41 +01:00
|
|
|
local jobs = {}
|
|
|
|
local time = 0.0
|
2019-03-27 21:05:50 +01:00
|
|
|
local time_next = math.huge
|
2017-01-22 11:17:41 +01:00
|
|
|
|
|
|
|
core.register_globalstep(function(dtime)
|
2017-04-02 10:51:16 +02:00
|
|
|
time = time + dtime
|
2017-01-22 11:17:41 +01:00
|
|
|
|
2019-03-27 21:05:50 +01:00
|
|
|
if time < time_next then
|
2017-01-22 11:17:41 +01:00
|
|
|
return
|
|
|
|
end
|
|
|
|
|
2019-03-27 21:05:50 +01:00
|
|
|
time_next = math.huge
|
|
|
|
|
2017-01-22 11:17:41 +01:00
|
|
|
-- Iterate backwards so that we miss any new timers added by
|
2019-03-27 21:05:50 +01:00
|
|
|
-- a timer callback.
|
2017-01-22 11:17:41 +01:00
|
|
|
for i = #jobs, 1, -1 do
|
|
|
|
local job = jobs[i]
|
|
|
|
if time >= job.expire then
|
|
|
|
core.set_last_run_mod(job.mod_origin)
|
|
|
|
job.func(unpack(job.arg))
|
2019-03-27 21:05:50 +01:00
|
|
|
local jobs_l = #jobs
|
|
|
|
jobs[i] = jobs[jobs_l]
|
|
|
|
jobs[jobs_l] = nil
|
|
|
|
elseif job.expire < time_next then
|
|
|
|
time_next = job.expire
|
2017-01-22 11:17:41 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end)
|
|
|
|
|
|
|
|
function core.after(after, func, ...)
|
|
|
|
assert(tonumber(after) and type(func) == "function",
|
2019-03-17 10:25:47 +01:00
|
|
|
"Invalid minetest.after invocation")
|
2019-03-27 21:05:50 +01:00
|
|
|
local expire = time + after
|
2020-09-23 19:11:56 +02:00
|
|
|
local new_job = {
|
2017-01-22 11:17:41 +01:00
|
|
|
func = func,
|
2019-03-27 21:05:50 +01:00
|
|
|
expire = expire,
|
2017-01-22 11:17:41 +01:00
|
|
|
arg = {...},
|
2020-09-23 19:11:56 +02:00
|
|
|
mod_origin = core.get_last_run_mod(),
|
2017-01-22 11:17:41 +01:00
|
|
|
}
|
2020-09-23 19:11:56 +02:00
|
|
|
jobs[#jobs + 1] = new_job
|
2019-03-27 21:05:50 +01:00
|
|
|
time_next = math.min(time_next, expire)
|
2020-09-23 19:11:56 +02:00
|
|
|
return { cancel = function() new_job.func = function() end end }
|
2017-01-22 11:17:41 +01:00
|
|
|
end
|