diff --git a/main.lua b/main.lua index 40fc47f..215041f 100644 --- a/main.lua +++ b/main.lua @@ -1,59 +1,54 @@ oop = require("oop/oop") +local Types = require("oop/types") -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()) +local function attempt(label, fn) + local ok, err = pcall(fn) + if ok then + print(label .. ": ok") + else + print(label .. ": " .. err) end end -function PremiumAccount(cls) - cls.inherit(BankAccount) +local i = Types.Int(10) +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) - this.deposit(25) - this.audit() - end -end +print("Int:", i) +print("Float:", f) +print("Str:", s, "#", #s) +print("Bool:", b) +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) -acct.deposit(100) -acct.withdraw(30, 1234) +print("Int add:", i + Types.Int(5)) +print("Float mul:", f * Types.Float(2.0)) +print("Str concat:", s .. Types.Str("!")) +print("Bool eq:", b == Types.Bool(true)) -local vip = PremiumAccount("Sam", 9999) -vip.monthly_bonus() - -local ok, err = pcall(function() - vip.rotate_token() +attempt("Int mutate", function() + i.value = 99 +end) +attempt("Float mutate", function() + 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) -print("rotate_token from outside:", ok, err)