I have Lua objects which share a metatable which has a __eq
metamethod. Inside this meta method, I want to check if the two objects are the same object before even comparing them. Similar to how in java you would do a == b || a.compareTo(b)
. The issue though is by doing ==
inside of __eq
, it calls __eq
and thus Stack Overflow. How can I achieve this?
local t1 = { x = 3 }
local t2 = { x = 3 }
local t3 = t1
print(t1 == t3) -- true, they pointer to same memory
local mt = {
__eq = function(lhs, rhs)
if lhs == rhs then return true end -- causes stack overflow
return lhs.x == rhs.x
end
}
setmetatable(t1, mt)
setmetatable(t2, mt)
-- stack overflow below
print(t1 == t2) -- this should compare 'x' variables
print(t1 == t3) -- this shouldn't need to do so, same memory location