a = {, }
b= {, } vector2 = {}
function vector2.Add(v1, v2)
if(v1 == nil or v2 == nil)then
return nil
end
local res = {}
res[] = v1[] + v2[]
res[] = v2[] + v2[]
return res;
end vector2.__add = vector2.Add setmetatable(a, vector2)
setmetatable(b, vector2) res = a + b print(res[], res[])

元表操作的一般流程

1.定义原始表

2.定义元表

3.定义元方法

4.设置元表

 str1 = {"I", "love", "lua"}

 myStr = {}
function myStr.ToString(str)
res = {}
for i = , #str do
res[i] = str[i]
end
return table.concat(res, " ")
end myStr.__tostring = myStr.ToString setmetatable(str1, myStr) print(str1)
str2 = {str1 = "我",str2 = "爱", str3 = "撸啊"}
myStr = {}
function myStr.ToString(str)
res = {}
for i,v in pairs(str) do
res[#res+] = v
end return table.concat(res, " ")
end myStr.__tostring = myStr.ToString setmetatable(str2, myStr) print(str2)
teststr = {s1 = "", s2 = ""}

mytable = {}
function mytable.tips()
return "不存在"
end mytable.__index = mytable.tips; setmetatable(teststr, mytable) --TEST CODE
print(teststr["s1"])
print(teststr["s3"]) -- 输出不存在
 testStr = {a = "aaa", b = "bbb"}

 testStr.c = "ccc"   ---添加字段
print(testStr["c"]) ---输出ccc function AddValue(tab, k, v)
print( "你尝试访问的字段不存在"..k)
end setmetatable(testStr, {__newindex = AddValue}) --简化的元方法 testStr.d = "ddd" ---添加字段
print(testStr["d"]) --输出nil
myTab = {}
function TestMethod(tab, num1, num2)
return num1 + num2
end setmetatable(myTab, {__call = TestMethod}) a = myTab(, )
print(a) --输出3
05-11 09:23