From 3207366daab937bafe2029ee231257c51188d6b2 Mon Sep 17 00:00:00 2001 From: wm4 Date: Tue, 1 Apr 2014 00:36:04 +0200 Subject: lua: add mp.unregister_event() function Someone requested this... I think. --- DOCS/man/en/lua.rst | 5 +++++ player/lua/defaults.lua | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/DOCS/man/en/lua.rst b/DOCS/man/en/lua.rst index 2cf485ba35..34d1d0e8c3 100644 --- a/DOCS/man/en/lua.rst +++ b/DOCS/man/en/lua.rst @@ -235,6 +235,11 @@ The ``mp`` module is preloaded, although it can be loaded manually with See `Events`_ and `List of events`_ for details. +``mp.unregister_event(fn)`` + Undo ``mp.register_event(..., fn)``. This removes all event handlers that + are equal to the ``fn`` parameter. This uses normal Lua ``==`` comparison, + so be careful when dealing with closures. + ``mp.add_timeout(seconds, fn)`` Call the given function fn when the given number of seconds has elapsed. Note that the number of seconds can be fractional. As of now, the timer diff --git a/player/lua/defaults.lua b/player/lua/defaults.lua index 557a0ff4a7..a17e80a20f 100644 --- a/player/lua/defaults.lua +++ b/player/lua/defaults.lua @@ -235,6 +235,32 @@ function mp.register_event(name, cb) return mp.request_event(name, true) end +function mp.unregister_event(cb) + for name, sub in pairs(event_handlers) do + local found = false + for i, e in ipairs(sub) do + if e == cb then + found = true + break + end + end + if found then + -- create a new array, just in case this function was called + -- from an event handler + local new = {} + for i = 1, #sub do + if sub[i] ~= cb then + new[#new + 1] = sub[i] + end + end + event_handlers[name] = new + if #new == 0 then + mp.request_event(name, false) + end + end + end +end + -- default handlers mp.register_event("shutdown", function() mp.keep_running = false end) mp.register_event("script-input-dispatch", script_dispatch) -- cgit v1.2.3