在Lua中嵌套元表

在下面的代码中,我尝试在__index上嵌套元表,但它不起作用。我想要做的是,如果值为t1或t2,那么返回相应的值,否则调用最内层的__index上的函数。这可能吗?

因此,在下面的x["hello"]中,我可以返回值。我知道我可以在最外层的__index上使用函数,但似乎我应该可以使用嵌套的元表来解决这个问题。

谢谢。

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???

这个方法可以工作,但是我觉得我应该可以使用元表来做到这一点。

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"])

原文链接 https://stackoverflow.com/questions/5181002

点赞
stackoverflow用户416047
stackoverflow用户416047

这个代码可以运行,但我能不能不声明 mt2 就完成它呢?

x = { val = 3 }      -- 一个对象

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"])
2011-03-03 13:59:46
stackoverflow用户416047
stackoverflow用户416047

下面是使用嵌套元表的代码,并且附带了原始的 markdown 格式。感谢 Alexander 的提示,这让代码更清晰了。

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"])
2011-03-04 05:11:25