__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
本文深入探讨了Lua中元表__newindex的使用,通过实例展示了当__newindex为function和table时的不同行为,解释了如何通过rawset跳过__index调用,以及在metatable设置下对table数据操作的影响。

539

被折叠的 条评论
为什么被折叠?



