如何在 lua 的函数中获取函数的调用者?
具体来说,我正在寻找(用于命令输出中的调试目的,例如打印)在调用公共(public)函数时记录的能力,并指示它是从哪里调用的。
例如,这可能只是调用它的文件名
IE。
File 1 - Has commonly used function
File 2 - Calls of the the file one functions
PS Mud - 这样做时我实际上得到了零 - 那这正常吗?在这种情况下无法获得更多信息:
调用文件;
SceneBase = {}
function SceneBase:new(options)
end
return SceneBase
调用文件:
require("views.scenes.scene_base")
local scene = SceneBase.new()
最佳答案
debug.getinfo(2).name
如果它有一个并且它是一个字符串,它将给你调用函数的名称。如果它是一个匿名函数,你会得到 nil
,如果它使用非字符串键存储在表中,您将得到 ?
.
function foo() print(debug.getinfo(2).name) end
-- _G["foo"] => function name is a string
function bar() foo() end
bar() --> 'bar'
-- _G[123] => function name is a number
_G[123] = function() foo() end
_G[123]() --> '?'
-- function has no name
(function() foo() end)() --> 'nil'
关于lua - 如何在lua的函数中获取函数的调用者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10577633/