Lua实现__add方法重载示例
实现加法(__add)重载代码示例:
代码如下:
do local Infor_class = {}; function Infor_class.create(_t) local newTable = {}; setmetatable(newTable, Infor_class); --set the metatable for i, v in pairs(_t) do newTable[i] = v; end return newTable; end function Infor_class.sum(c1, c2) if(#c1 ~= #c2) then return nil; else local result = {}; local len = #c1; for i = 1, len do result[i] = c1[i] + c2[i]; end print("result"); return result; end print("nil"); return nil; end Infor_class.__add = Infor_class.sum --override the _add r1 = Infor_class.create{3, 4} r2 = Infor_class.create{5, 6}; result = r1 + r2; print(unpack(result)); end
相关推荐
waiwaiLILI 2020-10-09
ChaITSimpleLove 2020-07-26
程序媛一枚 2020-05-14
zhaowj00 2020-04-08
zhaowj00 2020-02-17
lemonzhangyan 2019-11-18
84590091 2019-11-09
mieleizhi0 2019-11-07
xiaofanguan 2019-04-12
极乐净土 2012-06-13
xudongdong 2019-07-01
zhll 2019-06-28
momode 2019-06-28
王甲评 2019-06-27
xxjoy 2019-06-27
BluewineY 2011-08-16
oDongTianShuiYue 2019-06-13
austindev 2019-06-13