Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

lua - get the list of parameter names of a function, from outside the function

I'm generating some (non-html) documentation for a Lua library that I developed. I will generate the documentation by hand, but I'd appreciate some kind of automation if possible (i.e. generating skeletons for each function so I can fill them in)

I'd like to know if there's a way for lua to know the names of the parameters that a function takes, from outside it.

For example, is there a way to do this in Lua?

function foo(x,y)
  ... -- any code here
end

print( something ... foo ... something)
-- expected output: "x", "y"

Thanks a lot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ok,here is the core code:

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

and you can use like this:

print(getArgs(fun))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...