lua __index元方法被不同的表调用。

我试图在运行时计算矩形的上、下、右和左属性,而不是将它们保留在表中。

Rect = {}

Rect.__index = Rect

setmetatable(Rect, {
            __index = function(tbl,key)
                if key == 'right' then
                  return tbl.x + tbl.width
                elseif key == 'top' then
                  return tbl.y
                elseif key == 'left' then
                  return tbl.x
                elseif key == 'bottom' then
                  return tbl.y + tbl.height
                end

                return rawget(tbl,key)
               end
})

function Rect.new(x, y, width, height)
    return setmetatable( { x = x, y = y, width = width, height = height }, Rect )
end

function Rect:intersectsWith(other)
    return not (other.left > self.right or other.right < self.left or other.top > self.bottom or other.bottom < self.top)
end

让我困惑的是:

如果

Rect.__index = Rect

是为了使实例能够回退到缺失方法的 Rect,那么我的自定义 __index 实现应该放在哪里呢?我尝试将其放在 Rect 的元表中,因为 __index 方法可以链接。

结果是,__index 被调用但调用的表是错误的。它崩溃了,因为 tbl.x 和 lua 不能对它执行算术运算。我的猜测是,传递的表是 Rect 表本身,因为调用是链接的。

点赞
用户646619
用户646619

Lua 在调用 __index 元方法之前会检查键是否在索引表中,因此 return rawget(tbl,key) 是多余的。

你实际想要的是 return Rect[key],这将像 __index=tbl 快捷方式一样在 Rect 表中查找值。

2014-08-06 17:41:34