Created
November 11, 2010 10:59
-
-
Save aurora/672346 to your computer and use it in GitHub Desktop.
inheritance -- Lua style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- number | |
number = {} | |
function number:new(o) | |
o = o or {} | |
setmetatable(o, self) | |
self.__index = self | |
self.__add = function(self, op) | |
return self:new{value=(self:cast(self) + self:cast(op))} | |
end | |
return o | |
end | |
function number:cast(op) | |
if (type(op) == 'table') then | |
return op.value | |
else | |
return op | |
end | |
end | |
n1 = number:new{value=10} | |
n2 = number:new{value=20} | |
print((n1 + n2).value) | |
-- money | |
money = number:new() | |
function money:cast(op) | |
if (self.currency ~= op.currency) then | |
error('unable to calculate with different currencies') | |
end | |
return number.cast(self, op) | |
end | |
m1 = money:new{value=10,currency='EUR'} | |
m2 = money:new{value=20,currency='EUR'} | |
m3 = money:new{value=30,currency='USD'} | |
sum = (m1 + m2) | |
print(sum.value) | |
print((sum + m3).value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment