"which object called this metamethod?" argument

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

"which object called this metamethod?" argument

Mason Bogue

I suggest that instead of the signature for metamethods like this:

function __add(left, right)

Lua could use this:

function __add(left, right, is_right)

where the last argument is set to `true` if and only if the metamethod
was called from the metatable of the right operand. When I use
operator overloading, I often find myself writing code like:

local mt = getmetatable(left)
if mt & mt.__add == [this function] then
  -- do stuff

This is annoying and also requires accessing the metatable twice:
first when the metamethod is invoked by Lua and again when the script
wants to know which object provided it. (Checking whether the
metatable equals a certain table only works if you do not use any

One particularly nice thing is that, since Lua function invocations
automatically discard extra arguments, adding this parameter should
not interfere with almost any existing Lua code (though it is possible
if the same function were reused as a metamethod and elsewhere, and it
will mess up metamethods written as C functions).

Of course no change is necessary for __unm, __tostring etc.



PS. A note that Lorenzo Donati's idea on my previous thread is better
than what I had suggested, although his explanation was far longer
than necessary. Sorry for ignoring it. And for making too many