after.lua 727 B

123456789101112131415161718192021222324252627282930313233
  1. local jobs = {}
  2. local time = 0.0
  3. core.register_globalstep(function(dtime)
  4. time = time + dtime
  5. if #jobs < 1 then
  6. return
  7. end
  8. -- Iterate backwards so that we miss any new timers added by
  9. -- a timer callback, and so that we don't skip the next timer
  10. -- in the list if we remove one.
  11. for i = #jobs, 1, -1 do
  12. local job = jobs[i]
  13. if time >= job.expire then
  14. core.set_last_run_mod(job.mod_origin)
  15. job.func(unpack(job.arg))
  16. table.remove(jobs, i)
  17. end
  18. end
  19. end)
  20. function core.after(after, func, ...)
  21. assert(tonumber(after) and type(func) == "function",
  22. "Invalid core.after invocation")
  23. jobs[#jobs + 1] = {
  24. func = func,
  25. expire = time + after,
  26. arg = {...},
  27. mod_origin = core.get_last_run_mod()
  28. }
  29. end