A Library using Teal

Creating and using a library in Teal.

The resulting files:

code> tree .
.
├── MyLib.lua
├── MyLib.tl
├── lib_demo.lua
└── lib_demo.tl

0 directories, 4 files

Library Designer - Creating the Library

Say you were asked to create a library that provides these functions:

You can do this using a Teal record.

-- MyLib.tl
-- A library example using Teal record.
--
-- base     is an important constant for the library; the library designer
--          provides this value and it cannot be changed.
-- offset   a value the user can change.

local base: integer = 40

local type MyLib = record
  offset: integer
  
  add:    function(integer, integer): integer
  addk:   function(integer): integer
end

MyLib.offset = 0   -- set default

function MyLib.add(x: integer, y: integer): integer
  return x + y
end

function MyLib.addk(x: integer): integer
  return base + MyLib.offset + x 
end

return MyLib

Library User

Invoking the Library

Say you were provided a library that performed normal addition and "special constant" addition. The code below shows how to invoke the library. Note how the user of the library can adjust the offset value.

-- lib_demo.tl
-- Demonstrating the use of a library.

local M = require "MyLib"

print(M.add(100, 2))    --> 102
print(M.addk(100))      --> 140

M.offset = 2
print(M.addk(100))      --> 142

Executing the Demo

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

code> tl run lib_demo.tl
102
140
142

Or you can generate Lua code:

code> tl gen *
Wrote: MyLib.lua
Wrote: lib_demo.lua

code> lua lib_demo.lua
102
140
142