Skip to content

Instantly share code, notes, and snippets.

@maritaria
Last active January 18, 2018 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maritaria/9ece6de6bf4fa2126cdceab97e87f266 to your computer and use it in GitHub Desktop.
Save maritaria/9ece6de6bf4fa2126cdceab97e87f266 to your computer and use it in GitHub Desktop.
local hooks = require("hooks") -- loads hooks.lua from same dir
hooks.add("test", "a", function(num) print("a", num) end)
hooks.add("test", "b", function(num) print("b", num + 2) end)
hooks.call("test", 4)
hooks.remove("test", "a")
hooks.call("test", 4)
local hooks = {} -- create a table to define the module on
local registry= {} -- local table to keep track of the registered hooks
-- Adds a callback to a hook. The callback needs an associated key so you can remove it later again.
-- The hookname is a string that indicates the list to add the callback to, the list is used by hooks.call
function hooks.add(hookname, key, callback)
registry[hookname] = registry[hookname] or {}
registry[hookname][key] = callback;
end
-- Removes a hook by its key
function hooks.remove(hookname, key)
if (registry[hookname]) then
registry[hookname][key] = nil
end
end
-- Invoke all callbacks on a specific hook
-- (...) is a shortcut for all remaining arguments
function hooks.call(hookname, ...)
if (registry[hookname]) then
for _, callback in pairs(registry[hookname]) do
callback(...)
end
end
end
--Return the module, this is what is given back by the require() function when this file is included
--We return the module table which means that all local variables in this file are private to the module and only the functions on the module table are exposed.
return hooks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment