Question

For example, can I declare a metamethod for __index which takes two arguments, then do something like myuserdata[somearg1, somearg2]? Not that I want to use it or that I have any idea of why it would be useful, I'm just wondering if in my library that deals with binding c++ to Lua I can and should enforce a right (except for __call metamethod of course) number of arguments of the function bound as metamethod.

Was it helpful?

Solution

Lua doesn't enforce parameter counts on functions in general: http://ideone.com/kAynR

That said, the metamethods which map to syntax are bound by the syntax - for instance, Lua syntax doesn't allow ,-separated values inside [] indexing:

luac: ']' expected near ','

OTHER TIPS

Lua functions can receive an arbitrary number of functions. This is true of your metamethods as well.

However, metatables don't let you change the arity of operators. A metamethod for unary operators (not, #, etc.) is only going to be passed on one argument. A metamethod for binary operators (+, %, ==, ^, .., etc.) is only going to be passed two arguments.

Table indexing operations are defined in the Lua grammar as taking one argument, so that's all you can use and all your metamethod for indexing will receive.

The only metamethod that may receive an arbitrary number of aruments is call.

No, the index operator can only take one argument, as in C++. While the function for the index operator can have as many arguments as you want, if you actually try to use more than one inside the [] you'll get an error.

It depends on the operator. So you neither can nor need to "enforce" that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top