Moop
Moop

Reputation: 3601

Get Reference to Calling Function in Lua

I know I can use debug.getinfo(1, "n").name to get the calling function's name, but I would like to get a reference to that function pointer itself.

For debug.getlocal(), the f parameter is the stack position so I can easily get the locals for the calling function by just choosing the correct index. But for debug.getupvalue(), the f parameter is the function pointer itself, which I don't have.

Here is a brief example, but with the offending line debug.getupvalue(someFunction, index) there to demonstrate what I would like to accomplish, without the hard-coded reference.

local someUpValue = "stackoverflow"

function someFunction()
    local value1 = "hi"
    local value2 = "there"
    local value3 = someUpValue

    log()
end

function log()
    local callingFuncName = debug.getinfo(2, "n").name

    local index = 1
    while(true) do
        local name, value = debug.getlocal(2, index)
        if name then
            print(string.format("Local of %s: Name: %s Value: %s", callingFuncName, name, value))                
        else
            break
        end
        index = index + 1
    end

    index = 1
    while(true) do
        local name, value = debug.getupvalue(someFunction, index)
        if name then
            print(string.format("Upvalue of %s: Name: %s Value: %s", callingFuncName, name, value))                
        else
            break
        end
        index = index + 1
    end
end

someFunction()

Upvotes: 2

Views: 882

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

You can use debug.getinfo(2, "f").func to get the function reference (assuming you are calling from the function you want to get a reference to):

function log()
    local callingFuncRef = debug.getinfo(2, "f").func
    callingFuncRef(false) -- this will call the function, so make sure there is no loop

Upvotes: 2

Related Questions