9

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..
Ryan Stein
  • 7,930
  • 3
  • 24
  • 38
Kosmetika
  • 20,774
  • 37
  • 108
  • 172
  • 1
    In the interest of avoiding the XY problem can you also provide some context of what you're trying to solve with this? – greatwolf Nov 24 '13 at 19:21

1 Answers1

9

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.

Ryan Stein
  • 7,930
  • 3
  • 24
  • 38
  • 1
    @Kosmetika I've edited my answer with a trick that you might like. Let me know how it works for you. – Ryan Stein Nov 24 '13 at 17:15
  • i'm using lua 5.1, but I'll try – Kosmetika Nov 24 '13 at 17:18
  • 1
    There are two special considerations: 1) You can call a function as a method, which adds 1 to the number of parameters (the `self` parameter), and 2) The last format parameter might be `...`, which is a list of an indeterminate number of parameters. – Tom Blodget Nov 24 '13 at 21:24