在 Lua 的表中实现回退/默认获取器。

有没有一种类似于 Python 的 __getitem__ 机制的实现方法?

例如,有以下代码:

local t1 = {a=1, b=2, c=3, d=4}

如果在代码中调用 t1.e,那么我希望返回的不是 nil,而是其他东西。

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

点赞
stackoverflow用户726361
stackoverflow用户726361

你可以使用 setmetatable__index 元方法:

local t1 = {a = 1, b = 2, c = 3, d = 4}

setmetatable(t1, {
    __index = function(table, key)
        return "something"
    end
})

print(t1.hi) -- 输出 "something"

注意,当你执行 t.nonexistant = something 时,不会调用该方法。为此,你需要使用 __newindex 元方法:

local t1 = {a = 1, b = 2, c = 3, d = 4}

setmetatable(t1, {
    __index = function(table, key)
        return "something"
    end,

    __newindex = function(table, key, value)
        rawset(table, tostring(key) .. '_nope', value)
    end
})

print(t1.hi) -- 输出 "something"
t1.hi = 'asdf'
print(t1.hi) -- 输出 "something"
print(t1.hi_nope) -- 输出 "asdf"
2011-12-13 13:08:38