lua-元表

    技术2022-07-11  77

    --元表:可以实现对2个table的操作,也可以实现改变table的行为,每个行为关联对应的元方法 --setmetatable(table,metatable):为table设置元表 --getmetatable(table):获取table的元表 table1 = {} metatale1 ={} setmetatable(table1,metatale1) --__Index元方法:用来对表访问。利用键来访问table的时候,如果这个键没有值,那么会寻找table的元表metatable,如果有元表,继续检查有没有_index键,如果有, --且包含一张表,则在该表格中查找相应的键 t1= setmetatable({},{__index={key1=3}}) print(t1.key1) --包含一个函数,会调用该函数,table和键作为参数传递给该函数 t2= setmetatable({key1="V1"},{__index=function(t2,key) if(key=="key2") then return "V2" else return nil end end}) print(t2.key1,t2.key2) print() --__newIndex元方法:用来对表更新。如果给表的一个缺少的索引赋值,解释器就会查找__newIndex元方法,如果存在,则调用该函数而不是给表进行赋值操作 meta3={} t3 = setmetatable({key1="V1"},{__newindex=meta3}) print(t3.key1) t3.key2 ="V2" print(t3.key2,meta3.key2) print() --__add元方法:2个表相加合并 --计算表中的元素个数 function table_maxn(t) local num = 0 for k,v in pairs(t) do if(num<k) then num = k end end return num end --2表相加合并 t4= setmetatable({1,2,3},{__add = function(t4,newtable) for i=1,table_maxn(newtable) do table.insert(t4,table_maxn(t4)+1,newtable[i]) end return t4 end}) t5 = {4,5,6} t4= t4+t5 for k,v in ipairs(t4) do print(k,v) end print() --__call元方法:计算表中元素的和 t6 = setmetatable({15},{ __call = function(t6,newtable) sum =0 for i=1,table_maxn(t6) do sum = sum +t6[i] end for i=1,table_maxn(newtable) do sum = sum + newtable[i] end return sum end }) t7 = {35,5} print(t6(t7)) print() --__tostring元方法:用于修改表的输出行为 t8 = setmetatable({10,45},{ __tostring = function(t8) sum = 0 for k,v in pairs(t8) do sum = sum + v end return "sum = "..sum end }) print(t8)
    Processed: 0.013, SQL: 9