types.Function.getarity
Method on every
functionReturns how many arguments the closure takes: the counts that getfuncinfos gives, without the names, defaults and type masks it collects.
Return value
A table with three keys:
num_params- the number of named parameters, withoutthisand the...tail; the same asgetfuncinfos().parameters.len() - 1num_required- how many of them have no default value, the same asnum_params - getfuncinfos().defparams.len()varargs-truewhen the closure ends in...
Notes
Use it where only the argument count matters, for example to select how many arguments to pass to a callback. getfuncinfos makes a table of 16 or 17 slots and 3 arrays on each call, and getarity makes one table of 3 slots.
A native closure without a declaration string reports max(abs(paramscheck), 1) - 1 for both counts, and varargs when paramscheck is 0 or less.
Example
function add(a, b = 10) { return a + b }
let { num_params, num_required, varargs } = add.getarity()
println($"add: num_params={num_params} num_required={num_required} varargs={varargs}")
let log = function(fmt, ...) { return [fmt].extend(vargv) }
println($"log: num_params={log.getarity().num_params} varargs={log.getarity().varargs}")
function callWithIndex(cb, value, index) {
return cb.getarity().num_params >= 2 ? cb(value, index) : cb(value)
}
println(callWithIndex(@(v) v * 2, 5, 1))
println(callWithIndex(@(v, i) v * i, 5, 3))Output:
add: num_params=2 num_required=1 varargs=false
log: num_params=1 varargs=true
10
15See also
getfuncinfos | Returns a table describing the closure: its name, parameters, and other introspection data the VM tracks for it. |
call | Calls the closure, using env as its this and forwarding the rest of the arguments as its own parameters. |
| function | class index |