访问 __eq 元方法中的指针?

Access to pointers inside __eq meta method?

我有 Lua 个共享一个元表的对象,该元表有一个 __eq 元方法。在这个元方法中,我想在比较它们之前检查这两个对象是否是同一个对象。与 java 中的方式类似 a == b || a.compareTo(b)。问题是通过在 __eq 中执行 ==,它会调用 __eq 并因此调用 Stack Overflow。我怎样才能做到这一点?

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

检查rawequal()函数。它会在不调用元方法的情况下比较实例。

无需在 __eq 元方法内部测试相等性,因为 Lua 仅在用户数据指针不同时调用 __eq 元方法。

在设置元表后立即添加 print(t1 == t3) 以确认这一点。

manual 说(强调):

__eq: the equal (==) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are either both tables or both full userdata and they are not primitively equal.