在lua嵌套metatables

时间:2011-03-03 13:00:16

标签: lua

在下面的代码中,我试图在__index上嵌套metatable,但它没有用。我想要做的是,如果值是t1或t2然后返回相关的值,否则调用最里面的__index上的函数。这可能吗?

所以在下面的x ["你好"]中我可以返回一个值。我知道我可以在最外面的__index上使用一个函数,但似乎我应该能够以某种方式使用嵌套的元表来实现。

TIA。

x = { val = 3 }      -- our object

mt = {
    __index = {
        t1 = 2,
        t2 = 3,
        __index = function (table, key)
            print("here"..key)
            return table.val
        end
    }
    }

setmetatable(x, mt)
print(x["t1"]) -- prints 2
print(x.t2) -- prints 3
print(x["hello"]) -- prints nil???

这有效,但似乎我可以用metatables

来做
x = { val = 3 }      -- our object

mt1 = {
        t1 = 2,
        t2 = 3
    }

mt = {
        __index = function (table, key)
            local a = mt1[key]
            if a == nil then
                print("here"..key)
                a = "test"
            end
            return a
        end
}

setmetatable(x, mt)
print(x["t1"])
print(x.t2)
print(x["hello"])

2 个答案:

答案 0 :(得分:1)

..对于在家里跟随的人,这里是嵌套的metatables inline。感谢亚历山大提示让它更清洁。

x = setmetatable(
    { val = 3 },
    {
        __index = setmetatable({
                t1 = 2,
                t2 = 3
            },
            {
            __index = function (table, key)
                print("here"..key)
                return key
            end
            }
        )
    }
)
print(x["t1"])
print(x.t2)
print(x["hello"])

答案 1 :(得分:0)

这有效,但是我可以在不声明mt2的情况下进行吗?

x = { val = 3 }      -- our object

mt2 = {
        __index = function (table, key)
                print("here"..key)
            return key
        end
}

mt = {
        __index = {
        t1 = 2,
        t2 = 3
        }
}

setmetatable(mt.__index, mt2)
setmetatable(x, mt)
print(x["t1"])
print(x.t2)
print(x["hello"])