版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22990635/article/details/78058384
__index用于lua中table的查询;
__newindex用于lua中table的更新。当一个table中不存在的索引赋值时,解析器就会查找__newindex元方法。如果有这个元方法,解析器就会调用它,而不是进行赋值。如果这个元方法是一个table,解析器就在此table中执行赋值,而不是对原来的table赋值。
有元方法__newindex
local t1 = {}
local mt = {
__index = smartMan,
__newindex = function(table, key, value)
print(key .. " not exist "..value);
end
}
setmetatable(t1, mt)
t1.sayHello = "sfsdsfsf"
print("6666666=====",t1.sayHello)
无元方法__newindex
local t1 = {}
local mt = {
__index = smartMan,
-- __newindex = function(table, key, value)
-- print(key .. " not exist "..value);
-- end
}
setmetatable(t1, mt)
t1.sayHello = "sfsdsfsf"
print("6666666=====",t1.sayHello)