From e3e9661a33e9c810a6f6be6cd76978d1c2df9ec4 Mon Sep 17 00:00:00 2001 From: wm4 Date: Wed, 2 Apr 2014 17:09:45 +0200 Subject: lua: give more control over timers Now they can be paused and resumed. Since pausing and disabling the timer is essentially the same underlying operation, we also just provide one method for it. mp.cancel_timer probably still works, but I'm considering this deprecated, and it's removed from the manpage. (We didn't have a release with this function yet, so no formal deprecation.) --- player/lua/defaults.lua | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) (limited to 'player/lua/defaults.lua') diff --git a/player/lua/defaults.lua b/player/lua/defaults.lua index a17e80a20f..512fe0cb54 100644 --- a/player/lua/defaults.lua +++ b/player/lua/defaults.lua @@ -144,6 +144,9 @@ end local timers = {} +local timer_mt = {} +timer_mt.__index = timer_mt + function mp.add_timeout(seconds, cb) local t = mp.add_periodic_timer(seconds, cb) t.oneshot = true @@ -155,15 +158,33 @@ function mp.add_periodic_timer(seconds, cb) timeout = seconds, cb = cb, oneshot = false, - next_deadline = mp.get_time() + seconds, } - timers[t] = t + setmetatable(t, timer_mt) + t:resume() return t end -function mp.cancel_timer(t) - if t then +function timer_mt.stop(t) + if timers[t] then timers[t] = nil + t.next_deadline = t.next_deadline - mp.get_time() + end +end + +function timer_mt.kill(t) + timers[t] = nil + t.next_deadline = nil +end +mp.cancel_timer = timer_mt.kill + +function timer_mt.resume(t) + if not timers[t] then + local timeout = t.next_deadline + if timeout == nil then + timeout = t.timeout + end + t.next_deadline = mp.get_time() + timeout + timers[t] = t end end @@ -186,17 +207,17 @@ local function process_timers() if not timer then return end - local wait = timer.next_deadline - mp.get_time() + local now = mp.get_time() + local wait = timer.next_deadline - now if wait > 0 then return wait else if timer.oneshot then - timers[timer] = nil + timer:kill() + else + timer.next_deadline = now + timer.timeout end timer.cb() - if not timer.oneshot then - timer.next_deadline = mp.get_time() + timer.timeout - end end end end -- cgit v1.2.3