lua: add convenience function for hooks

So the user doesn't have to care about the awkward low-level details.
This commit is contained in:
wm4 2014-10-21 00:15:30 +02:00
parent 131633b4e5
commit 40d6b5ca85
2 changed files with 47 additions and 0 deletions

View File

@ -734,3 +734,29 @@ List of events
``chapter-change``
The current chapter possibly changed.
Extras
------
This documents experimental features, or features that are "too special" and
we don't guarantee a stable interface to it.
``mp.add_hook(type, priority, fn)``
Add a hook callback for ``type`` (a string identifying a certain kind of
hook). These hooks allow the player to call script functions and wait for
their result (normally, the Lua scripting interface is asynchronous from
the point of view of the player core). ``priority`` is an arbitrary integer
that allows ordering among hooks of the same kind. Using the value 50 is
recommended as neutral default value. ``fn`` is the function that will be
called during execution of the hook.
Currently existing hooks:
``on_load``
Called when a file is to be opened, before anything is actually done.
For example, you could read and write the ``stream-open-filename``
property to redirect an URL to something else (consider support for
streaming sites which rarely give the user a direct media URL), or
you could set per-file options with by setting the property
``file-local-options/<option name>``. The player will wait until all
hooks are run.

View File

@ -399,6 +399,27 @@ function mp.osd_message(text, duration)
mp.commandv("show_text", text, duration)
end
local hook_table = {}
local hook_registered = false
local function hook_run(id, cont)
local fn = hook_table[tonumber(id)]
if fn then
fn()
end
mp.commandv("hook_ack", cont)
end
function mp.add_hook(name, pri, cb)
if not hook_registered then
mp.register_script_message("hook_run", hook_run)
hook_registered = true
end
local id = #hook_table + 1
hook_table[id] = cb
mp.commandv("hook_add", name, id, pri)
end
function mp.format_table(t, set)
if not set then
set = { [t] = true }