我正在为我开发的 Lua 库生成一些(非 html)文档。我将手动生成文档,但如果可能的话,我会很感激某种自动化(即为每个功能生成骨架,以便我可以填写它们)
我想知道 lua 是否有办法从函数外部知道函数所采用的参数的名称。
例如,有没有办法在 Lua 中做到这一点?
function foo(x,y)
... -- any code here
end
print( something ... foo ... something)
-- expected output: "x", "y"
Run Code Online (Sandbox Code Playgroud)
非常感谢。
小智 7
好的,这是核心代码:
function getArgs(fun)
local args = {}
local hook = debug.gethook()
local argHook = function( ... )
local info = debug.getinfo(3)
if 'pcall' ~= info.name then return end
for i = 1, math.huge do
local name, value = debug.getlocal(2, i)
if '(*temporary)' == name then
debug.sethook(hook)
error('')
return
end
table.insert(args,name)
end
end
debug.sethook(argHook, "c")
pcall(fun)
return args
end
Run Code Online (Sandbox Code Playgroud)
你可以这样使用:
print(getArgs(fun))
Run Code Online (Sandbox Code Playgroud)
看看debug.getinfo,但您可能需要一个解析器来完成此任务。我不知道有什么方法可以在不实际运行函数并检查其环境表的情况下从 Lua 中获取函数的参数(请参阅debug.debug和debug.getlocal)。