Sometimes you have a project which you need to hook into another.
An example. - Last year I posted a backup tool which uses parameter sliders (defined in setup
). I needed to include this sliders into other projects, but didn’t want to initialize its setup
code by hand everytime (through classes and such). Therefor I needed a hook, which does that job automatically for me (just select the project dependency and have it appear).
CodeaCommunity had such a hook (=autorun function); realized with debug.sethook()
, but it wasn’t flexible enough. You couldn’t join multiple projects together, it worked only for one include.
Here's my try at solving this task:
Normally when writing two functions with the same name, the second overrides the first.
function setup()
print("Hello World")
end
function setup()
print("Welcome") -- This gets printed!
end
My hook module appropriates this. Try to run the code above again (each function in its own tab), this time together with the module code from below. - You will notice that both setup
functions are run and printed!
It even accounts their order! Even when joining multiple projects into one, it hooks them in the right order, in which the dependencies were selected!
--# Main
function setup()
print("hooks are awesome^^")
end
--# Hooks
-- Module by kennstewayne.de [jack0088@me.com]
--
-- Write hooks inside separate tabs, because 'Main' tab can't be included into other projects!
-- A hook function must have the same name as the target function you want to hook into!
-- Include 'Hooks' tab into every project, which should use hooks!
-- Currently you can only hook into 'setup', but you might extend this easily for 'draw', 'touched', etc.
local setup_hooks = {}
debug.sethook(function(eventName, lineNumber)
if setup and setup ~= prev then
print("debug: hook found")
local _setup = setup
if _setup ~= setup_hooks[#setup_hooks] then
table.insert(setup_hooks, _setup)
end
setup = function()
print("debug: 'setup' overriden")
debug.sethook()
for id, func in ipairs(setup_hooks) do
print("debug: run hook...")
func()
end
end
prev = setup
end
end, "r")
It’s very difficult to tell and show its usage. But hooks are awesome thing! - You have to try! In the meantime I’ll might create a video wich shows some fields of application…