Skip to content

Instantly share code, notes, and snippets.

@GlorifiedPig
Last active April 21, 2023 12:12
Show Gist options
  • Save GlorifiedPig/d5740d7f4c8d6164e980bdbee74e20a9 to your computer and use it in GitHub Desktop.
Save GlorifiedPig/d5740d7f4c8d6164e980bdbee74e20a9 to your computer and use it in GitHub Desktop.
Lua Hook Library
--- A library used for calling and attaching hooks.
-- @module Hook
Hook = {}
local cachedHooks = {}
--- Attaches a function to a hook.
-- @string hookID The string ID of the hook to be attached to.
-- @string uniqueID The unique ID of the function you are attaching to the hook.
-- @func func The function to be called when the hook is called.
-- @usage Hook.Attach( "FooHook", "UniqueID", FunctionInput )
function Hook.Attach( hookID, uniqueID, func )
if not cachedHooks[hookID] then
cachedHooks[hookID] = {}
end
cachedHooks[hookID][uniqueID] = func
end
--- Calls all of a hook's attached functions.
-- @string hookID The name of the hook to call.
-- @param[type=varargs] ... The arguments you want to pass to the hook.
-- @return The value of the first hook that returns something.
-- @usage Hook.Call( "FooHook" )
function Hook.Call( hookID, ... )
if cachedHooks[hookID] then
local valueToReturn
for k, v in pairs( cachedHooks[hookID] ) do
local returnValue = v( ... )
if returnValue ~= nil and valueToReturn == nil then valueToReturn = returnValue end
end
return valueToReturn
end
end
--- Removes a hook attachment from it's table.
-- @string hookID The name of the hook to remove from.
-- @string uniqueID The hook you are removing.
-- @usage Hook.Remove( "FooHook", "UniqueID" )
function Hook.Remove( hookID, uniqueID )
if cachedHooks and cachedHooks[hookID] and cachedHooks[hookID][uniqueID] then
cachedHooks[hookID][uniqueID] = nil
end
end
--- Returns a table of all the hooks.
-- @return The table of registered hooks.
-- @usage Hook.GetAll()
function Hook.GetAll()
return cachedHooks
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment