我们都知道在C++中,可以通过重载运算符来实现代码的简练。在lua中我们也可以实现类似的操作。先举个例子:
local cood = {}
function cood:new(x,y)
local o = {}
setmetatable(o,self)
o.x = x
o.y = y
return o
end
cood.__add=function (a,b)
local x = a.x+b.x
local y = a.y+b.y
return cood:new(x,y)
end
local a = cood:new(1,2)
local b = cood:new(3,4)
local c = a+b
print(c.x,c.y)
可以看到,我们通过重载”+”运算符来实现了两个对象的简单相加,输出如下:
4 6
除了”+”运算符之外,lua还提供一下的运算符让我们重载
__add: 对+进行重载
__sub: 对-进行重载
__mul: 对*进行重载
__div: 对/进行重载
__unm: 对相反数进行重载
__mod: 对%进行重载
__pow: 对^进行重载
__concat: 对连接操作符进行重载
__eq: 对==进行重载
__lt: 对<进行重载
__le: 对<=进行重载
在以后的编码中,我们就可以利用运算符的重载,来简化一些操作了。