Lua question

Is there a way to hook up a callback to a function?

That is, say I have functions a(), b(). I want to write something that would let me do

bindCallback(a,b)

Then whenever a is called, at the end (or at the start, either way could work for me), b is called as well. Of course I could just make a() call b() directly but that’s not ideal because I only want the callback binding to be active in certain circumstances, or later on I might bind a to a different callback c(), etc.

I don’t know if this works 100% because i haven’t tested it, but you get the idea.

function bindCallback(original, callback)
    if old == nil then old = {} end

    -- use global table 'old' to store a map from the newly defined function to the original so it can be recovered the next time bindCallback is called
    if old[original] ~= nil then
        original = old[original]
    end    

    newFunction = function(...)
        original(unpack(arg))
        callback()
    end

    old[newFunction] = original

    return newFunction
end

-- somewhere else
someFunction = bindCallback(someFunction, function() print("Callback stuff!") end

You could also define unbindCallback(a,b) that returns the original function.

genius John, I think that works. Thanks!