Reputation: 13
I want to overload the == (equality) operator for <number> == <table>
and <table> == <number>
expressions.
However, it seems to me that Lua only uses the __eq
metamethod when the two sides of the equation are of the same type.
For instance, the following snippet does not work as I expected
x = {1,2}
setmetatable (x, {__eq = function (x,y) print "!" return x[y] ~= nil end})
print (x == 1)
but this one does:
x = {1,2}
setmetatable (x, {__eq = function (x,y) print "!" return x[y] ~= nil end})
print (x == {1})
Is it possible to implement ==
for <number> == <table>
and <table> == <number>
expressions?
I'm running the latest version (5.2.2).
Upvotes: 1
Views: 283
Reputation: 122383
It's not possible.
If two objects have different basic types, the equality operation results in false
, without even calling the metamethod.
Upvotes: 2
Reputation: 72312
It is not possible to override equality for values of different types.
Upvotes: 1