This appendix is a map for readers who already know another language. It does not teach Teascript from scratch, since the chapters on the guide already do that. Instead, it lists what to expect, what looks familiar, and, above all, what looks familiar but behaves differently.
Teascript is a small, dynamically typed, garbage-collected language with a C-like block syntax. Its values and its embedding API will feel familiar to programmers embedding Lua in C, and its classes and collections to Python programmers. C programmers will find that most of the control flow is what they are used to, minus declarations and memory management, of course.
Syntax at a Glance
The table below shows how the same constructs are written in each language.
| Teascript | C | Python | Lua | |
|---|---|---|---|---|
| Comment | // text | // text | # text | -- text |
| Variable | var x = 1 | int x = 1 | x = 1 | local x = 1 |
| Constant | const x = 1 | const int x = 1 | by convention | local x <const> = 1 |
| No value | nil | NULL | None | nil |
| Logic | and or not | && || ! | and or not | and or not |
| Not equal | != | != | != | ~= |
| Conditional | c ? a : b | c ? a : b | a if c else b | c and a or b |
| Exponent | x ** y | pow(x, y) | x ** y | x ^ y |
| If | if x > 0 {} | if(x > 0) {} | if x > 0: | if x > 0 then ... end |
| Counting loop | for var i = 0; i < n; i += 1 {} | for(int i = 0; i < n; i++) {} | for i in range(n): | for i=0, n-1 do ... end |
| Loop over items | for var x in items { } | for x in items: | for _, x in ipairs(items) do | |
| Function | function f(a, b) { } | int f(int a, int b) { } | def f(a, b): | function f(a, b) ... end |
| Anonymous function | (x) => x * 2 | lambda x: x * 2 | function(x) return x * 2 end | |
| Join strings | "a" + "b" | strcat(a, b) | "a" + "b" | "a" .. "b" |
| String with values | "n = ${n}" | printf("n = %d", n) | f"n = {n}" | "n = " .. n |
| List | [1, 2, 3] | int a[] = {1, 2, 3}; | [1, 2, 3] | {1, 2, 3} |
| Map | { a = 1, [k] = 2 } | {"a": 1, k: 2} | { a = 1, [k] = 2 } | |
| First item | list[0] | a[0] | lst[0] | lst[1] |
| Number of items | list.len | len(lst) | #lst | |
| Create an instance | Point.new(1, 2) | Point(1, 2) | usually Point.new(1, 2) | |
| Import | import math | #include <math.h> | import math | local math = require("math") |
Coming from C
There are no types to declare
A variable is introduced with var or const and holds a value of any type; the type belongs to the value. Variables must still be declared before use, and a name used before its declaration is a compile-time error.
All numbers are double-precision floats.
There is no separate integer type. In particular / is always real division:
print(10 / 3) // 3.3333...
The bitwise operators (&, |, ^, ~, <<, >>) are the usuals, and behave like their C counterparts on integer values.
Memory is managed for you
Strings, lists, maps and instances are all garbage collected. There is nothing to allocate, nothing to free, and no pointers in the language itself.
Strings are values, not arrays of char
They are immutable and carry their own length, so they may contain embedded zero bytes, and == compares their contents (identity). Indexing a string gives a one character string, and not a number.
Blocks always use braces, and conditions need no parentheses
The body of every if, while, do while, for and function must be a braced block, and semicolons are not needed to end a statement. They are only used to separate the three parts of a counting for:
for var i = 0; i < 10; i += 1
{
print(i)
}There is no ++ or --
Use i += 1. The compound assignments +=, -=, *=, /=, %=, **=, &=, |=, ^=, <<= and >>= exist.
Logic operators are words
Use and, or and not (! is accepted as well). Like in C, and and or short-circuit, but they return one of their operands rather than a 0 or 1.
Collections are built-in
Where you would reach for an array, a struct or a hash table implementation, you can use a list, a class or a map. Lists grow on demand and are bounds-checked; indexing outside of a list raises an error instead of reading arbitrary memory.
There are no headers
Code is split into modules, and anything a module wants to share has to be marked export. See chapter on the module system.
Embedding is a first-class feature
The interpreter is written in C, with a public API declared mainly in tea.h. A host program creates a state with tea_open, runs code, and exchanges values with scripts through a stack. The chapters of Part III cover this in depth; if you have used Lua, the section “Coming from Lua” at the end of this appendix shows a translation table.
Coming from Python
Blocks use braces, not indentation
Whitespace is not significant.
Variables must be declared
Assigning to a name that has not been introduced with var or const is an error, not an implicit declaration. A consequence of that is that closures can modify the variables they capture directly, without anything like nonlocal:
function make_counter()
{
var count = 0
return () => {
count += 1
return count
}
}is tests the type, not identity
In Teascript, x is Number or x is Animal asks whether a value is an instance of a class, including its superclasses. There is no operator for object identity. The global function rawequal can be used.
Strings are sequences of bytes
They are not sequences of Unicode code points. Text that needs to be processed by character is handled with the UTF-8 module. As in Python, there is no implicit conversion between numbers and strings; "hi" + 5 is an error. Instead of f-strings, strings interpolate expressions with ${...}:
print("2 + 3 = ${2 + 3}")Triple quoted strings exist, but they are raw; escape sequences are not interpreted inside them.
There are no tuples, sets or comprehensions
A list serves also as a tuple, and returning a list is how a function returns several values; the caller then unpacks it:
function min_max(list) { /* ... */ }
var lo, hi = min_max([3, 1, 4])In place of comprehensions, use the map and filter methods of lists with lambdas.
Lists and maps have different spellings
The length is the len property rather than a len() function. Appending is add, not append. Slices follow [start:end:step], but the start index must be written.
Maps are not ordered
Unlike a Python dictionary, iteration does not follow insertion order. Entries are written { name = value }, where a bare name on the left becomes a string key, and any other key goes in square brackets: { [1] = "one" }. Reading a missing key is an error, like a KeyError; the get method takes a default instead.
Classes are similar, with different names
| Python | Teascript |
|---|---|
Point(1, 2) | Point.new(1, 2) |
def __init__(self, x, y): | new(x, y) |
def area(self): | function area() |
self as first parameter | self is implicit |
@staticmethod | static name() |
@property | a getter, name { ... } |
__add__, __eq__, __getitem__ | operator +, operator ==, operator [] |
__str__ | tostring |
__getattr__ | getattr |
__call__ | call |
__contains__ | contains |
__iter__ | iter |
class B(A): | class B : A |
Inheritance is single only, and all fields are public. There are no private members.
Iteration is simple
An iterator is just a function that returns the next value on each call and nil when it is done, so it cannot produce nil itself. Such functions are usually closures. See the chapter on iterators.
Modules are files, and exports are explicit
Everything declared at the top level of a module is private unless it is marked export. A module is run only once, however many files import it.
Coming from Lua
The syntax is C-like, and there are no then, do or end
Blocks are enclosed in braces, and elseif is written else if.
Indexes start at zero
The first item of a list is list[0], and the length is list.len, not #list. Negative indexes count from the end: list[-1] is the last item.
Lists and maps are separate types
There is no table. [1, 2, 3] is a list and { a = 1 } is a map, each with its own methods. The syntax of map literals is the same as that of Lua tables with named keys. A list or a map can be a key, but nil cannot be.
Several operators mean something else
| Operator | Lua | Teascript |
|---|---|---|
.. | concatenation | range, as in 1..10 |
+ on strings | error | concatenation |
^ | exponent | bitwise XOR |
~ | bitwise NOT or XOR | bitwise NOT |
~= | not equal | not available, use != |
// | floor division | comment |
# | length | not an operator |
Variables are declared, and are local by default
In Lua, a name that has not been declared is a global; in Teascript, it is an error. var corresponds to local, with the difference that a top-level var is private to its module, not global.
Multiple return values are lists
A function returns one value. To return several, return a list, which the caller can unpack in a declaration:
var lo, hi = min_max(values)If there are fewer values than variables the remaining ones are nil, and if there are more the excess is discarded, as in Lua. A variadic parameter, ...args, is a list instead of a ... expression.
Closures work the same way
Functions capture variables, not values, and closures that capture the same variable share it.
Classes replace metatables
Classes are part of the language, with constructors, inheritance and self. The meta methods correspond roughly to metamethods:
| Lua | Teascript |
|---|---|
__add, __eq, __lt | operator +, operator ==, operator < |
__index, __newindex as functions | getattr, setattr |
__index, __newindex on t[k] | operator [], operator []= |
__call | call |
__tostring | tostring |
Methods are always called with a dot, obj.method(), which also binds self. There is no : syntax.
The iterative for is the same idea
Lua’s for calls an iterator function until it returns nil, and so does Teascript’s. The difference is that the iterator takes no arguments: there are no state or control values, and closures keep the state instead. for var k, v in map takes the place of for k, v in pairs(t).
A string buffer replaces table.concat
The Buffer class builds strings incrementally. join on a list covers the simple cases.
Modules are not tables returned by require
A module is a file; import "path" binds it to a variable named after the file, and its exported names are reached through it. Names that are not exported stay private.
The C API
The C API is built on the same stack model as Lua’s, and names correspond closely, with the tea_ prefix and a T for the state. Three differences are worth remembering:
- Stack indexes start at 0. The first argument of a C function is at index
0, andtea_upvalue_index(0)is the first upvalue. Negative indexes count from the top, as in Lua. - A C function returns nothing. Its type is
void (*)(tea_State* T), and it returns a result by pushing it. There is no count of return values. - Argument counts are declared when the function is registered.
tea_push_cfunctiontakes the number of required and of optional arguments, and the call is checked before the function is entered.
| Lua | Teascript |
|---|---|
luaL_newstate, lua_close | tea_open, tea_close |
luaL_loadfile, lua_pcall | tea_load_file, tea_pcall |
lua_pushnumber, lua_tonumber | tea_push_number, tea_get_number |
luaL_checknumber | tea_check_number |
lua_gettop, lua_settop | tea_get_top, tea_set_top |
lua_pushcfunction, lua_pushcclosure | tea_push_cfunction, tea_push_cclosure |
lua_upvalueindex | tea_upvalue_index |
lua_setglobal, lua_getglobal | tea_set_global, tea_get_global |
luaL_Reg, luaL_newlib | tea_Reg, tea_create_module |
lua_newtable | tea_new_map, tea_new_list |
lua_next | tea_next |
lua_newuserdata, luaL_checkudata | tea_new_udata, tea_check_udata |
lua_error | tea_error |
LUA_REGISTRYINDEX | TEA_REGISTRY_INDEX |
Where to Go from Here
If you have skimmed this appendix, the chapters on Types and Values and Functions are the best place to continue, since they contain most of the differences noted above. The rules of the language are stated precisely in the Language Specification.