我有 Lua 对象,它们共享一个具有元方法的元表__eq
。在这个元方法中,我想在比较它们之前检查这两个对象是否是同一个对象。类似于你在 java 中的做法a == b || a.compareTo(b)
。但问题是通过在==
内部进行__eq
,它调用__eq
并因此调用堆栈溢出。我怎样才能做到这一点?
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