1 a = {1, 2} 2 b= {3, 4} 3 4 vector2 = {} 5 function vector2.Add(v1, v2) 6 if(v1 == nil or v2 == nil)then 7 return nil 8 end 9 local res = {} 10 res[1] = v1[1] + v2[1] 11 res[2] = v2[1] + v2[2] 12 return res; 13 end 14 15 vector2.__add = vector2.Add 16 17 setmetatable(a, vector2) 18 setmetatable(b, vector2) 19 20 res = a + b 21 22 print(res[1], res[2])
元表操作的一般流程
1.定义原始表
2.定义元表
3.定义元方法
4.设置元表
1 str1 = {"I", "love", "lua"} 2 3 myStr = {} 4 function myStr.ToString(str) 5 res = {} 6 for i = 1, #str do 7 res[i] = str[i] 8 end 9 return table.concat(res, " ") 10 end 11 12 myStr.__tostring = myStr.ToString 13 14 setmetatable(str1, myStr) 15 16 print(str1)
str2 = {str1 = "我",str2 = "爱", str3 = "撸啊"} myStr = {} function myStr.ToString(str) res = {} for i,v in pairs(str) do res[#res+1] = v end return table.concat(res, " ") end myStr.__tostring = myStr.ToString setmetatable(str2, myStr) print(str2)
teststr = {s1 = "123", s2 = "456"} mytable = {} function mytable.tips() return "不存在" end mytable.__index = mytable.tips; setmetatable(teststr, mytable) --TEST CODE print(teststr["s1"]) print(teststr["s3"]) -- 输出不存在
1 testStr = {a = "aaa", b = "bbb"} 2 3 testStr.c = "ccc" ---添加字段 4 print(testStr["c"]) ---输出ccc 5 6 7 function AddValue(tab, k, v) 8 print( "你尝试访问的字段不存在"..k) 9 end 10 11 setmetatable(testStr, {__newindex = AddValue}) --简化的元方法 12 13 testStr.d = "ddd" ---添加字段 14 print(testStr["d"]) --输出nil
myTab = {} function TestMethod(tab, num1, num2) return num1 + num2 end setmetatable(myTab, {__call = TestMethod}) a = myTab(1, 2) print(a) --输出3