diff --git a/builtin/common/after.lua b/builtin/common/after.lua index 321e5ac9d5def..268e53a5fc94b 100644 --- a/builtin/common/after.lua +++ b/builtin/common/after.lua @@ -107,6 +107,7 @@ end local function remove_first_jobs() local removed_expiry = heap_pop(expiries) local removed = job_map[removed_expiry] + removed.elapsed_time = removed_expiry job_map[removed_expiry] = nil return removed end @@ -117,6 +118,12 @@ local time_next = math.huge core.register_globalstep(function(dtime) time = time + dtime + for _, job in pairs(job_map) do + if job.elapsed_time then + job.elapsed_time = job.elapsed_time + dtime + end + end + if time < time_next then return end @@ -151,6 +158,7 @@ local function dummy_func() end function job_metatable.__index:cancel() self.func = dummy_func self.args = {n = 0} + self.elapsed_time = nil end function core.after(after, func, ...) @@ -160,10 +168,14 @@ function core.after(after, func, ...) local new_job = { mod_origin = core.get_last_run_mod(), func = func, + elapsed_time = time, args = { n = select("#", ...), ... }, + get_elapsed_time = function(self) + return self.elapsed_time + end } local expiry = time + after diff --git a/doc/lua_api.md b/doc/lua_api.md index a43f517a00f6f..4c0064c918ff4 100644 --- a/doc/lua_api.md +++ b/doc/lua_api.md @@ -6699,6 +6699,9 @@ Timing * Jobs set for earlier times are executed earlier. If multiple jobs expire at exactly the same time, then they are executed in registration order. +* `job:get_elapsed_time()` + * Returns the game time passed since the job was launched, in `dtime_s`. + * Returns `nil` if the job is cancelled. * `job:cancel()` * Cancels the job function from being called