【发布时间】:2018-07-13 17:30:03
【问题描述】:
我有 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
【问题讨论】:
标签: lua meta-method