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)
原文地址:https://www.cnblogs.com/blackteeth/p/10164369.html
时间: 2024-10-13 12:00:25