Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get arity of a function

I'm a JavaScript developer who's learning Lua. I'm stuck with a problem of getting a function's arity in the Lua language.

In JavaScript, it's simple:

function test (a, b) {}
console.log(test.length) // 2

How is it possible to do it this easily in Lua?

function test (a, b) end
print(#test) -- gives an error..
like image 601
Kosmetika Avatar asked Nov 24 '13 16:11

Kosmetika


People also ask

What is method arity?

Arity (/ˈærɪti/ ( listen)) is the number of arguments or operands taken by a function, operation or relation in logic, mathematics, and computer science.

What is arity in Python?

The arity of a function or an operation is the number of arguments or operands that the function or operation takes. The term was derived from words like "unary", "binary", "ternary", all ending in "ary". The asterisk "*" is used in Python to define a variable number of arguments.

What is arity function in JavaScript?

Arity (from Latin) is the term used to refer to the number of arguments or operands in a function or operation, respectively. You're most likely to come across this word in the realm of JavaScript when it's used to mention the number of arguments expected by a JavaScript function.

What is arity in math?

arity (plural arities) (logic, mathematics, computer science) The number of arguments or operands a function or operation takes. For a relation, the number of domains in the corresponding Cartesian product.


1 Answers

This is possible only through the debug library, but it is possible.

print(debug.getinfo(test, 'u').nparams) -- number of args
print(debug.getinfo(test, 'u').isvararg) -- can take variable number of args?

Please see here and here for more information.


Edit: Just in case you wanted to play with some black magic...

debug.setmetatable(function() end, {
    __len = function(self)
        -- TODO: handle isvararg in some way
        return debug.getinfo(self, 'u').nparams
    end
})

This will make it possible to use the # length operator on functions and provide a JavaScript-esque feel. Note however that this will likely only work in Lua 5.2 and above.

like image 122
Ryan Stein Avatar answered Sep 19 '22 20:09

Ryan Stein