kikito
kikito

Reputation: 52621

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.

Upvotes: 5

Views: 15891

Answers (5)

abner
abner

Reputation: 91

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))

Upvotes: 9

Sygmei
Sygmei

Reputation: 465

function GetArgs(func)
    local args = {}
    for i = 1, debug.getinfo(func).nparams, 1 do
        table.insert(args, debug.getlocal(func, i));
    end
    return args;
end

function a(bc, de, fg)
end

for k, v in pairs(GetArgs(a)) do
  print(k, v)
end

will print

1   bc
2   de
3   fg

Basically we use debug.getinfo to retrieve the nparams attribute (which gives us the information of how many parameters the function takes) and debug.getlocal to access the name of the parameters.

Tested and working with Lua 5.4

Upvotes: 3

Judge Maygarden
Judge Maygarden

Reputation: 27573

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).

Upvotes: 3

lhf
lhf

Reputation: 72312

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

Upvotes: 4

RBerteig
RBerteig

Reputation: 43296

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...

Upvotes: 1

Related Questions