Quirrel4.53.0

types.Function.getarity

Method on every function
nodiscard function.getarity(): any

Returns 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:

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

examples/types/function/getarity.nut
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
15

See also

getfuncinfosReturns a table describing the closure: its name, parameters, and other introspection data the VM tracks for it.
callCalls the closure, using env as its this and forwarding the rest of the arguments as its own parameters.
functionclass index