我知道我可以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()