2

我知道我可以debug.getinfo(1, "n").name用来获取调用函数的名称,但我想获取对该函数指针本身的引用。

对于debug.getlocal()f参数是堆栈位置,因此我只需选择正确的索引即可轻松获取调用函数的局部变量。但是对于debug.getupvalue()f参数是函数指针本身,我没有。

这是一个简短的示例,但其中有问题的行debug.getupvalue(someFunction, index)是为了演示我想要完成的工作,而没有硬编码的参考。

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()
4

1 回答 1

1

您可以使用debug.getinfo(2, "f").func来获取函数引用(假设您从要获取引用的函数中调用):

function log()
    local callingFuncRef = debug.getinfo(2, "f").func
    callingFuncRef(false) -- this will call the function, so make sure there is no loop
于 2018-02-12T02:58:43.143 回答