A Class using Teal

Creating and using a class in Teal.

The resulting files:

code> tree .
.
├── accounts.lua
├── accounts.tl
├── accounts_demo.lua
└── accounts_demo.tl

0 directories, 4 files

Class Designer - Creating the Class

Say you were asked to implement the object-oriented example provided in "Programming in Lua", 4th ed.; Ch21 - "Object-Oriented Programming":

Field:

Methods:

You can do this using a Teal record.

-- inspired by "Programming in Lua", 4th ed.;
-- Ch 21 "Object-Oriented Programming"

local type Account = record
  balance: number

  new:      function(amt: number): Account
  deposit:  function(self: Account, amt: number)
  withdraw: function(self: Account, amt: number)
end

function Account.new(amt: number): Account
  local self: Account = setmetatable({}, {__index = Account })
  self.balance = amt or 0
  return self
end

function Account:deposit(amt: number)
  self.balance = self.balance + amt
end

function Account:withdraw(amt: number)
  self.balance = self.balance - amt
end

return Account

Class User

Invoking the Class

Say you were provided a class that created instances of 'account'. The code below shows how to invoke the class and create and use instances.

-- use the account class
local Account = require "accounts"

local a1 = Account.new(100)        -- open account with 100
local a2 = Account.new(500)
a1:deposit(40)
a1:withdraw(10)
a2:deposit(50)
print(a1.balance)                   -- 100 + 40 - 10 = 130
print(a2.balance)                   -- 500 + 50      = 550

Executing the Demo

You can execute your demo by invoking the tl 'run' command:

code> tl run accounts_demo.tl
130
550

Or you can generate Lua code:

code> tl gen accounts.tl
Wrote: accounts.lua

code> tl gen accounts_demo.tl
Wrote: accounts_demo.lua

code> lua accounts_demo.lua
130
550