Lua 更多元方法
示例
元方法还有很多,其中一些是算术的(例如加法,减法,乘法),还有按位运算(和,或,或,移位),比较(<,>)以及基本类型运算,例如==和#(相等和长)。让我们构建一个支持许多这些操作的类:对有理算术的调用。尽管这是非常基本的,但它说明了这个想法。
local meta = {
-- string representation
__tostring = function(self)
return string.format("%s/%s", self.num, self.den)
end,
-- addition of two rationals
__add = function(self, rhs)
local num =self.num*rhs.den+rhs.num* self.den
local den =self.den* rhs.den
return new_rational(num, den)
end,
-- equality
__eq = function(self, rhs)
returnself.num==rhs.numandself.den== rhs.den
end
}
-- a function for the creation of new rationals
function new_rational(num, den)
local self = { num = num, den = den }
setmetatable(self, meta)
return self
end
local r1 = new_rational(1, 2)
print(r1) -- 1/2
local r2 = new_rational(1, 3)
print(r1 + r2) -- 5/6
local r3 = new_rational(1, 2)
print(r1 == r3) -- true
-- this would be the behaviour if we hadn't implemented the __eq metamethod.
-- this compares the actual tables, which are different
print(rawequal(r1, r3)) -- false
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短