-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.lua
41 lines (32 loc) · 1010 Bytes
/
hook.lua
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
-- when a Hook object is called, all functions registered with the hook will be called (regardless of what they return)
-- when a registered function returns some non-nil value(s), they will be passed back to the caller. if more than one registered function returns values, it is an error.
local C = Class()
function C:init(name)
self.name = name -- for debugging
self.hooks = {}
end
function C:register(func)
table.insert(self.hooks, func)
end
function C:registerBound(inst, funcname)
self:register(function(...) return inst[funcname](inst, ...) end)
end
function C:__call(...)
local ret
for _, func in ipairs(self.hooks) do
local r = table.pack(func(...))
for i = 1, r.n do
if r[i] ~= nil then
if ret then
error('multiple functions returned values, when only one is allowed to')
end
ret = r
break
end
end
end
if ret then
return table.unpack(ret)
end
end
return C