-- -- hook.lua -- -- Written by [aka]bomb, 2022 -- -- Permission is hereby granted, free of charge, to any person obtaining a copy of -- this software and associated documentation files (the "Software"), to deal in -- the Software without restriction, including without limitation the rights to -- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do -- so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. -- local hook = {} local error = error local print = print local string_format = string.format local tostring = tostring hook.hooks = {} local hook_hooks = hook.hooks function hook.add(eventname, hookname, func) if type(func) ~= "function" then error("bad argument #3 (function expected, got " .. type(func) .. ')') end local ehooks = hook_hooks[eventname] if ehooks == nil then hook_hooks[eventname] = { { hookname, func } } else table.insert(ehooks, { hookname, func }) end end function hook.call(eventname, ...) local ehooks = hook_hooks[eventname] if ehooks == nil then return end for i=1,#ehooks do local v = ehooks[i][2](...) if v ~= nil then return v end end end function hook.remove(eventname, hookname) local ehooks = hook_hooks[eventname] if ehooks == nil then return end for i=1,#ehooks do if ehooks[i][1] == hookname then ehooks[i] = nil break end end end function hook.print(eventname) local ehooks = hook_hooks[eventname] if ehooks == nil then return end if #ehooks == 0 then print("event '" .. eventname .. "' has no attached hooks") return end for i=1,#ehooks do local h = ehooks[i] print(string_format("%d.\t%s\t%s", i, tostring(h[1]), tostring(h[2]))) end end return hook