2
votes

I have functions inside a Lua table t and I learned that I can list all the functions the t contains by running the following script:

for k, v in pairs(t) do
  print(k, v)
end

It will for example print:

myfunction1 function: 0x107219805
myfunction2 function: 0x10721c194
myfunction3 function: 0x1071e067c

Now, I would like to know if it's possible to get each function's number of arguments it expects. So the result can be like the following:

myfunction1 function: 0x107219805 arguments: 3
myfunction2 function: 0x10721c194 arguments: 4
myfunction3 function: 0x1071e067c arguments: 5

Would this be possible in Lua? Or using the C API?

2
Which result do you expect, if the function has an variable amount of arguments (...)? Anyway I don't think this is possible.csaar
What's your Lua version?Egor Skriptunoff
@EgorSkriptunoff Lua 5.3Zack Lee
Regardless of the information available via the debug library, you won't get very far without the function's documentation. Same applies to the possible return lists of the function. A function is a value that you can call with any number of parameters of any type and get returned a list of any length and type, with the behavior (including usage of parameters and number and meaning of return list elements) varying from call to call. Well planned, useful functions have good documentation and use these features in an intelligible way. debug.getinfo is, itself, an example of this.Tom Blodget

2 Answers

5
votes

For Lua 5.2+ see the answer of lhf.

This is a solution for Lua 5.1 only
(you can combine the two solutions into one)

local function get_numparams_isvararg(func)
   -- returns num_param (number), is_vararg (boolean)
   local s = string.dump(func)
   assert(s:sub(1, 6) == "\27LuaQ\0", "This code works only in Lua 5.1")
   local int_size = s:byte(8)
   local ptr_size = s:byte(9)
   local pos = 14 + ptr_size + (s:byte(7) > 0 and s:byte(13) or s:byte(12 + ptr_size)) + 2 * int_size
   return s:byte(pos), s:byte(pos + 1) > 0
end

Usage example:

local function f(a, b, c, ...)
end

local function g()
end

print(get_numparams_isvararg(f))  --> 3  true
print(get_numparams_isvararg(g))  --> 0  false
3
votes

The call debug.getinfo(f) returns a table containing information about f. In particular,

  • debug.getinfo(f).nparams gives the number of parameters in f
  • debug.getinfo(f).isvararg tells whether f accepts a variable amount of arguments