您的位置:首页 > 编程语言 > Lua

lua中的元方法__index __newIndex

2017-09-21 23:58 288 查看
__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)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: