当前位置:首页 >> 脚本专栏

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