Lua - get a list of function parameter names, outside the function

I am creating some (non-html) documentation for the Lua library that I developed. I will generate documentation manually, but I would appreciate some automation (i.e. Generate skeletons for each function so that I can fill them)

I would like to know if there is a way for lua to find out the parameter names that the function executes from outside.

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"

Many thanks.

+2
source share
4 answers

Look debug.getinfo, but you probably need a parser for this task. I do not know how to get function parameters from Lua without actually starting the function and checking its environment table (see debug.debugand debug.getlocal).

+3

-. Lua 5.2 debug.getlocal.

+4

ok, :

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

:

print(getArgs(fun))
+4

Take a look at the luadoc utility . This is similar to Doxygen, but for Lua. It is intended so that the documentation is written in accordance with the source code, but it could certainly be used to create a template for the documentation structure, which will be highlighted separately. Of course, the template engine will leave you with a maintenance problem in the future ...

+1
source

Source: https://habr.com/ru/post/1751349/


All Articles