Lua实现__add方法重载示例
实现加法(__add)重载代码示例:
do localInfor_class={};
functionInfor_class.create(_t) localnewTable={}; setmetatable(newTable,Infor_class);--setthemetatable fori,vinpairs(_t)do newTable[i]=v; end returnnewTable; end
functionInfor_class.sum(c1,c2) if(#c1~=#c2)then returnnil; else localresult={}; locallen=#c1; fori=1,lendo result[i]=c1[i]+c2[i]; end print("result"); returnresult; end print("nil"); returnnil; end
Infor_class.__add=Infor_class.sum--overridethe_add
r1=Infor_class.create{3,4} r2=Infor_class.create{5,6};
result=r1+r2; print(unpack(result)); end