lua中的元方法__index __newIndex

来源:互联网 发布:淘宝运营岗位要求 编辑:程序博客网 时间:2024/06/05 04:05

__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)