Skip to content

Instantly share code, notes, and snippets.

@Silverfeelin
Last active December 12, 2022 15:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Silverfeelin/3a6286d443d829eed58fa781790e2de5 to your computer and use it in GitHub Desktop.
Save Silverfeelin/3a6286d443d829eed58fa781790e2de5 to your computer and use it in GitHub Desktop.
Starbound hook function
--- UNLICENSED: FEEL FREE TO USE THIS CODE WITH OR WITHOUT THIS HEADER.
-- https://gist.github.com/Silverfeelin/3a6286d443d829eed58fa781790e2de5
-- Usage: hook("init", myTable.myInit)
-- Prevent loading if another scriptHooks has been loaded (i.e. same script in a different folder)
if hook then return end
local hooks = {}
--- Loops over all functions in hook.
-- Returns the first non-nil value after calling all hooks.
local function loop(hook, ...)
local ret
for _,v in ipairs(hook) do
local r = v(...)
if type(ret) == "nil" then ret = r end
end
return ret
end
--- Creates a new empty hook for the given global function.
-- The return hook is a key-based table for functions to call.
local function createHook(name)
if hooks[name] then return hooks[name] end
local hook = {}
hooks[name] = hook
if _ENV[name] then
local old = _ENV[name]
_ENV[name] = function(...)
old(...)
return loop(hook, ...)
end
else
_ENV[name] = function(...)
return loop(hook, ...)
end
end
return hook
end
--- Hook a function to the global function.
-- @param name Global function name.
-- @param func Function to hook.
function hook(name, func)
local hook = createHook(name)
table.insert(hook, func)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment