含义:
1、__index (理解一点:就是在表里查找key)
设置以后在找元素时会在元表里找,顺序为
-1、主表里找key,key不到执行-2
-2、元表里找key,若key没有,则返回nil,有并且是表再执行-1,有不是表则直接返回
2、__newindex(用于修改和添加key)
设置在找不到元素以后在表里添加,具体看代码
3、rawset这是忽略__index具体用法在__newindex里,看代码
local t1 = {}(创建一个空表) local tIndex1 = function()
print("This is tIndex1 ") key1= "this is key1" end
local tnewIndex = function(type,key,value) print("This is tnewIndex") rawset(type,key,value) (这里设置rawset意思是:在type表中,设置key,value键值对,忽略运行type中的__index方法,就是很直接的赋值而已) end
local t2 = { __index = tIndex1, __newindex = tnewIndex }
setmetatable(t1,t2)(设置t2是t1的元表)
print(t1.key1)(查看打印日志)
t1.key1 = 50(设置t1的key值为50) print(t1.key1)(查看打印日志)
print(tIndex1)(查看打印日志)
这里的主要是在于:要弄清楚这里的key1是哪个key1,在t1.key1赋值之前,t1里面都是没有key1这个建的后来改的key1却是自己的key1与tIndex1没有瓜葛