元表
metatable:(元表)一组元操作(元方法)的集合;
__index:元方法之一,作用:定义了新的索引操作;
查找表的元方法,即metatable中的__index方法(也可以是另一个表)
原型:__index = fuunction(table,key) --此处的table为调用该元方法的
print("the key's value is nil!");
若对表中的key进行复制操作,执行该元方法(也可以是一个表);
原型:__newindex = function(table,key,value)
rawset(table,"bucunzide","geiyige");
--------------------------------------------------------------------------------------------
UIValueList = {name = "UIValueList"};
__index = function ( table,k )
__newindex = function ( table,k,value ) //table,调用者;k,索引;value,值
print("" .. value .. " ====");
setmetatable(UIValueList,UIValueMet);
-----------------------------------------------------------------------------------------
__add:元方法之一 ,作用类似于运算符重载,用于表之间的运算;
与__index、 __newindex 不同,操作符索引只能是函数。 它们接受的第一个参数总是目标表, 接着
是右值 (除了一元操作符"-",即索引__unm)。下面是操作符列表:
1)key值弱引用,只要其他地方没有对key值引用,那么,table自身的这个字段也会被删除。设置方法:setmetatable(t, {__mode = "k"});
2)value值弱引用,只要其他地方没有对value值引用,那么,table的这个value所在的字段也会被删除。设置方法:setmetatable(t, {__mode = "v"});
3)key和value弱引用,规则一样,但是key和value都同时生效,任意一个起作用时都会导致table的字段被删除。设置方法:setmetatable(t, {__mode = "kv"});
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | t = {};
-- 给t设置一个元表,增加__mode元方法,赋值为"k" setmetatable(t, {__mode = "k"});
-- 使用一个table作为t的key值 key1 = {name = "key1"}; t[key1] = 1; key1 = nil;
-- 又使用一个table作为t的key值 key2 = {name = "key2"}; t[key2] = 1; key2 = nil;
-- 强制进行一次垃圾收集 collectgarbage();
for key, value in pairs(t) do print(key.name .. ":" .. value); end |
------------------------------------------------------------------------
rawset(table,key,value) :设置表的索引
__index = fuunction(table,key)
--table[key] = 1000; 若此处直接使用key索引会再次调用__index方法,进入死循环;
rawset(table,key,1000); 使用rawset()方法可以直接设置新的键值对,从而避免调用__index和__newindex方法;
-----------------------------------------------------------------------
log_enum = { zhandouxitong = 4,
if type == log_enum.WujiangxitongServer then
local info = debug.getinfo(2,"nfSl");