有没有办法实现类似于python的__getitem__
?
例如,具有以下内容:
local t1 = {a=1, b=2, c=3, d=4}
如果在代码中调用t1.e
,那么我希望返回其他内容而不是nil
答案 0 :(得分:6)
您可以使用setmetatable
和__index
元方法:
local t1 = {a = 1, b = 2, c = 3, d = 4}
setmetatable(t1, {
__index = function(table, key)
return "something"
end
})
print(t1.hi) -- prints "something"
请注意,执行t.nonexistant = something
时不会调用此方法。为此,您需要__newindex
metamethod:
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) -- prints "something"
t1.hi = 'asdf'
print(t1.hi) -- prints "something"
print(t1.hi_nope) -- prints "asdf"