Advertisement
Guest User

timer.lua

a guest
Jan 19th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.25 KB | None | 0 0
  1. local ltimer = require("ltimer")
  2. local timer = {id = 0, max_id = 4294967295, pool = {}}
  3.  
  4. function timer.cancel(id)
  5.     if timer.pool[id] then
  6.         timer.pool[id] = nil
  7.         ltimer.delete(id)
  8.     end
  9. end
  10.  
  11. function timer.cancelall()
  12.     timer.pool = {}
  13.     ltimer.deleteall()
  14. end
  15.  
  16. local function timeout(elapse_, func_, once_)
  17.     if timer.id == timer.max_id then
  18.         id = 1
  19.     else
  20.         id = timer.id + 1
  21.     end
  22.     while timer.pool[id] do
  23.         id = id + 1
  24.         if id == timer.id then
  25.             error("timer id is used up")
  26.         end
  27.     end
  28.  
  29.     timer.id = id
  30.     timer.pool[id] = {elapse = elapse_, func = func_, once = once_}
  31.     ltimer.add(id, elapse_)
  32.     return id
  33. end
  34.  
  35. function timer.once(elapse, func)
  36.     return timeout(elapse, func, true)
  37. end
  38.  
  39. function timer.forever(elapse, func)
  40.     return timeout(elapse, func, false)
  41. end
  42.  
  43. function timer.expire()
  44.     ltimer.expire(function(id)
  45.         info = timer.pool[id]
  46.         if info then
  47.             if info.once then
  48.                 info.func()
  49.                 timer.pool[id] = nil
  50.             else
  51.                 ltimer.add(id, info.elapse)
  52.                 info.func()
  53.             end
  54.         end
  55.     end)
  56. end
  57.  
  58. ltimer.init()
  59.  
  60. return timer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement