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

前端 未结 4 1795
小鲜肉
小鲜肉 2021-01-01 07:31

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 p

相关标签:
4条回答
  • 2021-01-01 07:43

    Take a look at the luadoc utility. It is sort of like Doxygen, but for Lua. It is intended to allow the documentation to be written in-line with the source code, but it could certainly be used to produce a template of the documentation structure to be fleshed out separately. Of course, the template mechanism will leave you with a maintenance issue down the road...

    0 讨论(0)
  • 2021-01-01 07:48

    Take a look at debug.getinfo, but you probably need a parser for this task. I don't know of any way to fetch the parameters of a function from within Lua without actually running the function and inspecting its environment table (see debug.debug and debug.getlocal).

    0 讨论(0)
  • 2021-01-01 07:51

    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))
    
    0 讨论(0)
  • 2021-01-01 07:59

    Try my bytecode inspector library. In Lua 5.2 you'll be able to use debug.getlocal.

    0 讨论(0)
提交回复
热议问题