Repository navigation
Expand file tree
/
Copy pathhooks.lua
More file actions
73 lines (53 loc) · 1.55 KB
/
Copy pathhooks.lua
File metadata and controls
73 lines (53 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
local _M = {}
local hooks = {}
local ipairs = ipairs
local pack = table.pack
local unpack = table.unpack
local insert = table.insert
local function wrap_hook(f)
return function(acc, ...)
if acc and not acc[1] then
return acc
end
return pack(f(...))
end
end
-- Register a hook function.
-- @param name Name of the hook; names should be namespaced
-- so that they don't conflict: e.g. "dao:upsert:pre"
-- @param hook Hook function, which receives the arguments
-- passed to run_hook(). By default, if a previous hook function
-- returned nil, the hook function will not execute and
-- the return values from the previous one will be returned as
-- the result of run_hook().
-- @param opts Table of options:
-- * "low_level" - if true, hook is assumed to be a "low-level hook
-- function": the low-level function receives an array in
-- table.pack() format as the first argument and is expected
-- to return a similar array. It can decide to run even if
-- a previous hook failed.
function _M.register_hook(name, hook, opts)
assert(type(hook) == "function", "hook must be a function")
hooks[name] = hooks[name] or {}
local f
if opts and opts.low_level then
f = hook
else
f = wrap_hook(hook)
end
insert(hooks[name], f)
end
function _M.run_hook(name, ...)
if not hooks[name] then
return (...) -- return only the first value
end
local acc
for _, f in ipairs(hooks[name] or {}) do
acc = f(acc, ...)
end
return unpack(acc, 1, acc.n)
end
function _M.clear_hooks()
hooks = {}
end
return _M