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?
The call debug.getinfo(f) returns a table containing information about f. In particular,
debug.getinfo(f).nparams gives the number of parameters in fdebug.getinfo(f).isvararg tells whether f accepts a variable amount of argumentsFor 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With