1 -- account.lua |
|
2 -- from PiL 1, Chapter 16 |
|
3 |
|
4 Account = {balance = 0} |
|
5 |
|
6 function Account:new (o, name) |
|
7 o = o or {name=name} |
|
8 setmetatable(o, self) |
|
9 self.__index = self |
|
10 return o |
|
11 end |
|
12 |
|
13 function Account:deposit (v) |
|
14 self.balance = self.balance + v |
|
15 end |
|
16 |
|
17 function Account:withdraw (v) |
|
18 if v > self.balance then error("insufficient funds on account "..self.name) end |
|
19 self.balance = self.balance - v |
|
20 end |
|
21 |
|
22 function Account:show (title) |
|
23 print(title or "", self.name, self.balance) |
|
24 end |
|
25 |
|
26 a = Account:new(nil,"demo") |
|
27 a:show("after creation") |
|
28 a:deposit(1000.00) |
|
29 a:show("after deposit") |
|
30 a:withdraw(100.00) |
|
31 a:show("after withdraw") |
|
32 |
|
33 -- this would raise an error |
|
34 --[[ |
|
35 b = Account:new(nil,"DEMO") |
|
36 b:withdraw(100.00) |
|
37 --]] |
|
38 |
|