local mt = {} --定义mt.__add元方法(其实就是元表中一个特殊的索引值)为将两个表的元素合并后返回一个新表 mt.__add = function(t1,t2) local temp = {} for _,v inpairs(t1) do table.insert(temp,v) end for _,v inpairs(t2) do table.insert(temp,v) end return temp end local t1 = {1,2,3} local t2 = {2} --设置t1的元表为mt setmetatable(t1,mt)
local t3 = t1 + t2 --输出t3 local st = "{" for _,v inpairs(t3) do st = st..v..", " end st = st.."}" print(st)
local metaTable = {} -- 表合并 metaTable.__add = function (t1, t2) local temp = {} for i, v in pairs(t1) do table.insert(temp, v) end for i, v in pairs(t2) do table.insert(temp, v) end return temp end
__tostring
__tostring可以修改table转化为字符串的行为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
local metaTable = {} -- 打印方法(可以直接打印表) metaTable.__tostring = function(t) local s = "{" for i, v inipairs(t) do if i > 1then s = s..", " end s = s..v end s = s.."}" return s end -- 测试 local t = {"ab", "cd"} print(a) setmetatable(t,metaTable) print(a)
结果:
1 2
table: 0x14e2050 {ab, cd}
__call
__call可以让table当做一个函数来使用。
1 2 3 4 5 6 7 8 9 10 11 12 13
local mt = {} --__call的第一参数是表自己 mt.__call = function(mytable,...) --输出所有参数 for _,v inipairs{...} do print(v) end end