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
#!/usr/bin/lua | |
Account = { balance = 0 } | |
function Account:new (o) | |
print("Calling constructor for "..tostring(self)) | |
o = o or {} -- create object if user does not provide one | |
setmetatable(o, self) | |
-- self.__index = self | |
self.__index = function(table, key) | |
print("Accessing key = "..key.." for "..tostring(table).."; self = "..tostring(self)) | |
return self[key] | |
end | |
return o | |
end | |
function Account:deposit (v) | |
print("Account:deposit(): self = "..tostring(self)) | |
self.balance = self.balance + v | |
end | |
function Account:withdraw (v) | |
print("Account:withdraw(): self = "..tostring(self)) | |
if v > self.balance then error"insufficient funds" end | |
self.balance = self.balance - v | |
end | |
function Account:get_balance() | |
print("Account:get_balance(): self = "..tostring(self)) | |
return self.balance | |
end | |
SpecialAccount = Account:new() | |
function SpecialAccount:withdraw (v) | |
print("SpecialAccount:withdraw(): self = "..tostring(self)) | |
if v - self.balance >= self:getLimit() then | |
error"insufficient funds" | |
end | |
self.balance = self.balance - v | |
end | |
function SpecialAccount:getLimit () | |
print("SpecialAccount:getLimit(): self = "..tostring(self)) | |
return self.limit or 0 | |
end | |
s = SpecialAccount:new{limit=1000.00} | |
s:deposit(100.00) | |
s:withdraw(200) | |
print(s:get_balance()) |
kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$ ./inheritance.lua
Calling constructor for table: 0x2414180
Accessing key = new for table: 0x2412f40; self = table: 0x2414180
Calling constructor for table: 0x2412f40
Accessing key = deposit for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = deposit for table: 0x2412f40; self = table: 0x2414180
Account:deposit(): self = table: 0x2411eb0
Accessing key = balance for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = balance for table: 0x2412f40; self = table: 0x2414180
Accessing key = withdraw for table: 0x2411eb0; self = table: 0x2412f40
SpecialAccount:withdraw(): self = table: 0x2411eb0
Accessing key = getLimit for table: 0x2411eb0; self = table: 0x2412f40
SpecialAccount:getLimit(): self = table: 0x2411eb0
Accessing key = get_balance for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = get_balance for table: 0x2412f40; self = table: 0x2414180
Account:get_balance(): self = table: 0x2411eb0
-100
kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$
Notice how searching for a key is recursive. When a key is not found in s, it is searched in SpecialAccount. When the key is not found in SpecialAccount, it is searched in Account.