__newindex是一个function的情况:
local mt = {}
local mytable = setmetatable({bar = "1"}, mt)
mt.__index = function(table, key)
return "default"
end
mt.__newindex = function(table, key, value)
rawset(table, key, value)
end
--call "__newindex"
mytable.foo = "foo"
print(mytable.foo) -- print:foo
-- key is not find, call "__index"
print(mytable.far) -- print:"default"
-- skiped "__index"
print(rawget(mytable, mytable.par)) --print:nil
__newindex是一个table:
local t1 = {
foo = 3
}
local t2 = {}
local mytable = setmetatable({bar = 4}, {__newindex = t2, __index = t1})
print(mytable.bar, mytable.foo, mytable.par) -- 4 3 nil
mytable.newkey = "newkey"
print(mytable.newkey, t1.newkey, t2.newkey) -- nil nil newkey
mytable.bar = "bar"
print(mytable.bar, t1.bar, t2.bar) -- bar nil nil
mytable.foo = "foo"
print(mytable.foo, t1.foo, t2.foo) -- 3 3 foo