On this page

Scripting

Functions and tables

Functions and multiple returns

Functions are ordinary values, and they capture the variables around them (closures). Missing arguments arrive as nil and extra ones are dropped, as in Lua.

Multiple returns follow Lua 5.1: a call, method call or ... in the last position of a list expands to all of its values; anywhere else it gives just its first value.

LUA
local function divmod(a, b) return a // b, a % b end

local q, r = divmod(17, 5)      --> q = 3, r = 2
q, r = divmod(9, 2)             --> q = 4, r = 1
local x, y = divmod(9, 2), 7    --> x = 4, y = 7
local a, b, c = divmod(9, 2)    --> a = 4, b = 1, c = nil

The rules in full:

  1. Return lists. The last expression in a return passes on every value: return f(args) and return 0, f(args) both pass all of f's results, limited by how many the caller takes. return f(args) is also a proper tail call, so tail recursion runs in constant stack depth. Parentheses cut the list to one value, as in Lua: return (f()) returns exactly one.
  2. A call in the last position of a local declaration or assignment fills the remaining variables, padding with nil and dropping extras.
  3. A call in the last position of an argument list (including pcall's) or a table constructor expands too: g(f()) passes every value of f, and {f()} holds them all.
  4. Each expansion carries at most 250 values, and so does a whole argument list that one expands into; more is an error you can catch. So a function already holding 250 extra arguments can pass ... on alone, but not f(x, ...).
  5. The value your script returns to CoCoCo, and the value another script exports when you load it (Loading other scripts), are single values: the first, if there are several. A ctx function normally returns one value, but some return a result and an error (local res, err = f(...)) or several values. Functions that wait on the outside world return (ok, res) instead (Functions that wait on the outside world).

A function that returns a result and an error works like pcall, except the function decides what the error says:

LUA
local function parseQuantity(text: string): (number?, string?)
  local n = tonumber(text)
  if n == nil or n < 0 then return nil, "not a quantity" end
  return n, nil
end

local function total(text)
  local qty, err = parseQuantity(text)
  if not qty then return "failed: " .. tostring(err) end
  return qty * 5
end

total("4")    --> 20
total("x")    --> "failed: not a quantity"

Variable arguments (...). A function whose parameter list ends in ... takes any number of extra arguments. Inside it, ... is those arguments: select("#", ...) counts them, select(n, ...) gives them from position n, and {...} or table.unpack moves them around. ... follows the same rules as a call:

LUA
local function log(fmt, ...) return string.format(fmt, ...) end
log("%d/%d", 3, 4)            --> "3/4"

local function count(...) return select("#", ...) end
count("a", nil, "c")          --> 3

local function firstTwo(...)
  local a, b = ...            -- last position: fills two, padded with nil
  return a, b
end
local p, q = firstTwo(1)      --> p = 1, q = nil

local function pack(...) return {...} end
pack(1, 2, 3)                 --> {1, 2, 3}

A ... that isn't last (for example {..., x} or local a, b = ..., 7) gives one value, exactly like a call that isn't last. In the main script, ... holds the arguments CoCoCo passes. For most kinds of script that is the input, read with local input = ... (Where scripts run).

Tables

A table has two parts: a dense array part (keys 1…n, with #t == n) and a map part for every other key. A floating-point key with a whole value is the same key as the integer (t[1.0] is t[1]), and nil or NaN keys are errors.

Holes are defined (Lua leaves them unspecified): setting the last element to nil removes it; setting one in the middle to nil ends the array part there and moves the rest into the map part; and writing at #t + 1 appends, pulling in any map entries that continue the sequence.

LUA
local t = { "a", "b", "c" }
t[3] = nil
#t  --> 2
t[#t + 1] = "z"
t   --> {"a", "b", "z"}

Iteration is defined and repeatable. A generic for accepts exactly two forms, ipairs(expr) and pairs(expr), written directly in the loop. You can't pass iterators around, and redefining ipairs or pairs makes the loop an error rather than a different call.

  • ipairs(t) walks the array part in index order. The number of passes is fixed when the loop starts (in standard Lua it is live), so changing the array inside the loop doesn't change how many times it runs.
  • pairs(t) walks the array part in index order and then the map part in the order keys were added. Lua's order is unspecified; SwiftLua's is the same on every run and every platform.
  • pairs follows the table as it changes, by position: adding entries during the loop extends it, and removing one shifts the later entries. (Lua forbids adding during traversal; SwiftLua defines what happens instead.)
LUA
local keys = ""
for k in pairs({ 10, 20, zebra = 1, apple = 2 }) do
  keys = keys .. tostring(k) .. " "
end
keys  --> "1 2 zebra apple "

Table constructors ({1, 2, x = 3, [k] = v}) accept positional, named and computed fields, evaluated left to right.

Limited metatables. setmetatable(t, mt) and getmetatable(t) exist and honour three fields. __index (a table, or a function (t, k)) answers reads of keys t doesn't have, following a chain of tables; __newindex (a table, or a function (t, k, v)) receives writes to keys t doesn't have; and __tostring gives the text for tostring, print and inspect. A chain can be at most 8 tables long: longer, or circular, is an error. rawget(t, k) and rawset(t, k, v) bypass both hooks. pairs, #, table.size, the standard library and the values your script returns all see a table's own entries only. setmetatable refuses every other field (__eq, __call, __gc, __mode, __metatable, __len, __concat and the operator fields), so scripts can't redefine operators. Frozen tables can't have a metatable.

Operators do work on some types CoCoCo provides, such as Decimal (price * qty + shipping), but that is a separate mechanism, not a metatable, so writing an __add is refused even then. See "Sealed types" below.

Metatables are exactly enough for the usual class pattern:

LUA
local Account = {}
Account.__index = Account

function Account.new(owner)
  local self = setmetatable({}, Account)
  self.owner = owner
  self.balance = 0
  return self
end

function Account:deposit(amount)
  self.balance = self.balance + amount
  return self.balance
end

local acct = Account.new("Ada")
acct:deposit(50)  --> 50
acct:deposit(25)  --> 75

local Point = {}
Point.__index = Point
Point.__tostring = function(p) return "<Point " .. p.x .. "," .. p.y .. ">" end
tostring(setmetatable({ x = 1, y = 2 }, Point))  --> "<Point 1,2>"

Sealed types (operators)

Some types CoCoCo provides are sealed: only CoCoCo can create one, and it decides which operators work on it. Decimal, from the decimal library, is the main example:

LUA
local price, qty, shipping = decimal.new("19.99"), 3, decimal.new("4.95")
local total = price * qty + shipping   -- a Decimal: exact, no floating-point rounding
tostring(total)                        --> "64.92"
total > 0                              --> true
decimal.new("1") == decimal.new("1.000")  --> true
  • The checker knows the result types: Decimal + Decimal is a Decimal, and Decimal < Decimal is a boolean, so local t: Decimal = price * qty checks.
  • An integer works alongside a decimal (price * 3). A floating-point number doesn't: price + 0.1 is an error, because a binary fraction has no exact decimal value. That refusal is the point.
  • Comparison is by value, as the last line above shows.

Three things this is not. It isn't metatables: setmetatable refuses an __add whenever it is written. It isn't something a script can declare: only CoCoCo can seal a type. And it can't be forged: a sealed value carries a hidden mark that pairs, rawget and returned values never show and no script can set, so {units = 10, scale = 0} is not a decimal, however decimal-like it looks.

Loading other scripts

ctx.script.load(name) loads one of your stored Scripts while your script runs, and gives you what that Script returns, usually a table of functions:

LUA
local tax = ctx.script.load("tax")                          -- a stored Script, by name
local rules = ctx.script.load("rules_" .. input.region)     -- names can be worked out, too
if 100 >= rules.threshold then
  return tax.apply(100)
end
return 100

The Script you load ends with return, like this one, saved as tax:

LUA
local tax = {}
function tax.apply(amount: number): number return amount * 1.2 end
return tax
  • Names are looked up among your stored Scripts. There is no file system, no search path and no way to turn text into code. Pure scripts can't load other scripts.
  • A loaded Script's top level runs as part of your run, within your limits. Its one return value is what ctx.script.load gives you.
  • Each Script loads once per run: loading the same name again returns the same value. Separate runs load separately, so a Script's state never carries over between runs.
  • A Script that loads itself, directly or in a circle, is an error (moduleError), as is a name that isn't one of your Scripts (moduleNotFound). Both can be caught with pcall, for example to fall back when a Script is missing. There is a limit on how many Scripts one run can load (Limits).
  • Loaded Scripts share the run's globals, as in Lua, so a Script that changes a global changes it for the script that loaded it (and the checker reports creating one, as anywhere).
  • ctx.script.load is always called directly with one argument. Storing it (local load = ctx.script.load) isn't supported.
  • Loading may take a moment, while CoCoCo reads the Script from storage. Your call looks and behaves the same either way: the run simply waits for it (see Functions that wait on the outside world).
  • Checked across Scripts. When a Script is named literally (ctx.script.load("tax"), not ctx.script.load(name)), the checker reads its source to learn what it exports. So ctx.script.load("tax").aply is caught as a typo, and a Script's exported types (export type) can be named as mod.Name. Names worked out at run time aren't checked.

Method calls

receiver:name(args) works without metatables:

  • On a string, the method comes from the string library: s:upper() is string.upper(s), and ("%d!"):format(7) works.
  • On a table, it looks up the field and passes the table as the first argument: t:scale(4) is t.scale(t, 4).
  • On anything else it is an error. A missing method is a notCallable error.
  • The receiver is evaluated exactly once. The argument list is required: a:b on its own is an error, as in Lua.
LUA
("hello"):upper()          --> "HELLO"
("%d!"):format(7)          --> "7!"
local shape = { size = 3, scale = function(self, by) return self.size * by end }
shape:scale(4)             --> 12