Refactor main.lua: remove BankAccount and PremiumAccount implementations, retain type demonstrations

This commit is contained in:
Chipperfluff 2026-01-01 18:11:48 +01:00
parent 971cbbc8a2
commit 9fa895c696

View File

@ -1,59 +1,54 @@
oop = require("oop/oop") oop = require("oop/oop")
local Types = require("oop/types")
function BankAccount(cls) local function attempt(label, fn)
cls.setattr(cls, "owner", nil, cls.visibility.PUBLIC) local ok, err = pcall(fn)
cls.setattr(cls, "balance", nil, cls.visibility.PUBLIC) if ok then
cls.setattr(cls, "pin", nil, cls.visibility.PROTECTED) print(label .. ": ok")
cls.setattr(cls, "token", nil, cls.visibility.PRIVATE) else
print(label .. ": " .. err)
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
end end
function PremiumAccount(cls) local i = Types.Int(10)
cls.inherit(BankAccount) local f = Types.Float(2.5)
local s = Types.Str("hi")
local b = Types.Bool(true)
local t = Types.Tuple({ 1, 2, 3 })
local l = Types.List({ "a", "b" })
local q = Types.Queue({ 1, 2 })
local st = Types.Stack({ 9, 8 })
local d = Types.Dict({ one = 1, two = 2 })
local se = Types.Set({ "x", "y" })
function cls.monthly_bonus(this) print("Int:", i)
this.deposit(25) print("Float:", f)
this.audit() print("Str:", s, "#", #s)
end print("Bool:", b)
end print("Tuple:", t, "#", #t, "get2", t.get(2))
print("List:", l, "#", #l, "get1", l.get(1))
print("Queue:", q, "#", #q, "peek", q.peek())
print("Stack:", st, "#", #st, "peek", st.peek())
print("Dict:", d, "#", #d, "get(two)", d.get("two"))
print("Set:", se, "#", #se, "has(x)", se.has("x"))
local acct = BankAccount("Kim", 1234) print("Int add:", i + Types.Int(5))
acct.deposit(100) print("Float mul:", f * Types.Float(2.0))
acct.withdraw(30, 1234) print("Str concat:", s .. Types.Str("!"))
print("Bool eq:", b == Types.Bool(true))
local vip = PremiumAccount("Sam", 9999) attempt("Int mutate", function()
vip.monthly_bonus() i.value = 99
end)
local ok, err = pcall(function() attempt("Float mutate", function()
vip.rotate_token() f.value = 1.25
end)
attempt("Str mutate", function()
s.value = "nope"
end)
attempt("Bool mutate", function()
b.value = false
end)
attempt("Tuple mutate", function()
t.items[1] = 99
end) end)
print("rotate_token from outside:", ok, err)