[英]Get Reference to Calling Function in Lua
我知道我可以使用debug.getinfo(1, "n").name
來獲取調用函數的名稱,但我想獲得對該函數指針本身的引用。
對於debug.getlocal()
, f
參數是堆棧位置,因此我只需選擇正確的索引即可輕松獲取調用函數的debug.getlocal()
。 但是對於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()
您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.