60 lines
1.6 KiB
Lua
60 lines
1.6 KiB
Lua
oop = require("oop/oop")
|
|
|
|
function BankAccount(cls)
|
|
cls.setattr(cls, "owner", nil, cls.visibility.PUBLIC)
|
|
cls.setattr(cls, "balance", nil, cls.visibility.PUBLIC)
|
|
cls.setattr(cls, "pin", nil, cls.visibility.PROTECTED)
|
|
cls.setattr(cls, "token", nil, cls.visibility.PRIVATE)
|
|
|
|
cls.method("deposit", function(this, amount)
|
|
this.balance = this.balance + amount
|
|
print("deposit:", amount, "balance:", this.balance)
|
|
end, cls.visibility.PUBLIC)
|
|
|
|
cls.method("withdraw", function(this, amount, pin)
|
|
if pin ~= this.pin then
|
|
print("bad pin")
|
|
return
|
|
end
|
|
this.balance = this.balance - amount
|
|
print("withdraw:", amount, "balance:", this.balance)
|
|
end, cls.visibility.PUBLIC)
|
|
|
|
cls.method("audit", function(this)
|
|
print("audit:", this.owner, "balance:", this.balance)
|
|
end, cls.visibility.PROTECTED)
|
|
|
|
cls.method("rotate_token", function(this)
|
|
this.token = "t-" .. tostring(os.time())
|
|
print("token rotated")
|
|
end, cls.visibility.PRIVATE)
|
|
|
|
function cls.__init(this, owner, pin)
|
|
this.owner = owner
|
|
this.balance = 0
|
|
this.pin = pin
|
|
this.token = "t-" .. tostring(os.time())
|
|
end
|
|
end
|
|
|
|
function PremiumAccount(cls)
|
|
cls.inherit(BankAccount)
|
|
|
|
function cls.monthly_bonus(this)
|
|
this.deposit(25)
|
|
this.audit()
|
|
end
|
|
end
|
|
|
|
local acct = oop.new(BankAccount, "Kim", 1234)
|
|
acct.deposit(100)
|
|
acct.withdraw(30, 1234)
|
|
|
|
local vip = oop.new(PremiumAccount, "Sam", 9999)
|
|
vip.monthly_bonus()
|
|
|
|
local ok, err = pcall(function()
|
|
vip.rotate_token()
|
|
end)
|
|
print("rotate_token from outside:", ok, err)
|