On this page
Scripting
The standard library
The standard library
Only what is listed here exists, and every library table is frozen (writing to it is an
error). All the functions give the same results everywhere: there are no locale
settings, and the only clock and randomness are time.now() and uuid.v4/uuid.v7
(see "time" and "uuid" below). The other time and UUID functions always give the same
result for the same input.
Basic: assert(v [, message]); error([value [, level]]) (any value; level 2
blames the caller, 0 adds no position); type(v); tostring(v); tonumber(v [, base])
(reads a number from text, or passes a number through, and gives nil otherwise; it
never fails, so it works as a check; leading zeros and surrounding spaces are accepted,
base can be 2–36, and a 0x prefix reads hexadecimal; note that arithmetic still does
not convert strings); inspect(v); pcall(f, …) and xpcall(f, handler) (Errors and limits);
select("#" | n, …); unpack(t [, i [, j]]) (also table.unpack); rawequal(a, b);
_VERSION; and setmetatable, getmetatable, rawget, rawset (Tables).
tonumber("42") --> 42
tonumber(" 7 ") --> 7
tonumber("ff", 16) --> 255
tonumber("abc") --> nil
type(tonumber) --> "function"There's no print. Write to the run's log with ctx.log.info(message, attrs),
ctx.log.warn or ctx.log.error (The ctx reference).
The amount of log output is limited: going over the limit ends the run
(logLimitExceeded) and can't be caught.
inspect(v) shows a value's structure, for debugging. Tables appear as
{1, 2, key = value}: the array part first, then map entries in pairs order, with
names written bare and other keys in brackets. Strings are double-quoted with \n-style
escapes, nesting stops at depth 4 (<deep>) and loops are marked <cycle>. The format
is exact and the same on every platform, and never shows addresses or identities.
inspect({ 1, 2, name = "Ada", ["two words"] = true }) --> '{1, 2, name = "Ada", ["two words"] = true}'
inspect("line\nbreak") --> '"line\\nbreak"'math: floor, ceil, round (halves away from zero) and trunc (towards zero)
all return integers and are errors on overflow; round(x, places) rounds to 0–12
decimal places and returns a number; abs, min and max (any number of values),
sqrt; clamp(x, lo, hi) (reversed bounds are an error); sign(x) (−1, 0 or 1; NaN is
an error); lerp(a, b, t); approx(a, b, epsilon) (NaN is never approximately
anything); isinteger(x) (true for integers, and for numbers that are exactly whole);
fmod, modf, frexp, ldexp, deg and rad; exp, log(x [, base]), log10,
pow, sin, cos, tan, asin, acos, atan(y [, x]), atan2, sinh, cosh
and tanh; and the constants pi, huge, maxinteger and mininteger.
fmod to rad give exactly the same result everywhere. exp, log, pow and the
trigonometric and hyperbolic functions can differ in the last digit between platforms,
so compare their results with math.approx rather than ==. There is no
math.random: scripts give the same result every time they run.
math.round(2.5) --> 3
math.round(-2.5) --> -3
math.round(3.14159, 2) --> 3.14
math.clamp(15, 0, 10) --> 10
math.isinteger(4.0) --> true
math.max(3, 9, 4, 1) --> 9
math.fmod(7, 3) --> 1
math.deg(math.pi) --> 180.0
math.approx(math.sin(math.pi / 2), 1, 1e-12) --> truestring (counting bytes; see Values and types): len(s), upper(s), lower(s),
sub(s, i [, j]) (Lua's index rules; negative positions count from the end),
rep(s, n [, sep]), find(s, pattern [, init [, plain]]) (patterns: see below),
byte(s [, i [, j]]), char(…), format(fmt, …), split(s, sep) (the separator is
plain text and can't be empty; empty fields are kept), join(sep, list)
(table.concat with the separator first; elements must be strings or numbers),
isempty(s), lines(s) (splits on \n and drops one trailing \r per line, so Windows
line endings work; a final newline doesn't add an empty last line, and "" gives no
lines), trim, ltrim and rtrim (ASCII whitespace), startswith, endswith and
contains(s, part), replace(s, old, new [, count]) (plain text, never patterns; an
empty old is an error), padleft and padright(s, width [, fill]) (a single fill
character) and reverse(s) (reverses by character, the same on every platform).
upper and lower change the case of all letters, not just ASCII ones.
string.split("a,,b", ",") --> {"a", "", "b"}
string.join("-", { 1, 2, 3 }) --> "1-2-3"
string.lines("one\r\ntwo\n") --> {"one", "two"}
string.padleft("7", 3, "0") --> "007"
(" hi "):trim() --> "hi"
string.upper("straße é") --> "STRASSE É"
string.replace("a.b.c", ".", "/") --> "a/b/c"String patterns. SwiftLua supports the full Lua 5.4 pattern language: the
classes %a %d %s %w %l %u %p %c %x and their uppercase opposites, ., sets [..] and
[^..] with ranges, the repeats * + - ?, the anchors ^ and $, captures ()
(including position captures), the back-references %1–%9, %b and %f. Matching is
metered: a pattern that would take an extreme amount of backtracking ends the run
with patternComplexityExceeded, which pcall can't catch, while a badly formed
pattern is an ordinary error you can catch. The pattern functions:
find(s, pat [, init [, plain]])gives(start, end, captures…)(1-based, both ends included) ornil. It uses patterns unlessplainistrue.match(s, pat [, init])gives the captures as separate values (or the whole match when the pattern has none), ornil, as in Lua.captures(s, pat [, init])gives an array of the captures (position captures as integers), or{wholeMatch}if the pattern has none, ornil.matchall(s, pat)gives an array of every matching piece of text. It replaces Lua'sgmatch, because a genericforaccepts onlypairsandipairs(Tables).gsub(s, pat, repl [, n])gives(result, count).replcan be a string (%0is the whole match,%1–%9the captures and%%a literal%), a table looked up by the first capture, or a function called for each match (returning the replacement, ornil/falseto keep the original). Becausegsubreturns two values, wrap it in parentheses,return (string.gsub(s, " ", "-")), when you want only the text.
string.find("order-1042", "%d+") --> 7
string.match("order-1042", "(%a+)-(%d+)") --> "order"
string.matchall("a1 b22 c333", "%d+") --> {"1", "22", "333"}
local out, n = string.gsub("a-b-c", "-", "+") --> out = "a+b+c", n = 2Limits worth knowing:
string.formatsupports%d %i %u %c %o %x %X %e %E %f %g %G %q %s %%with the- + space # 0flags; width and precision are at most 99.%swrites the value astostringwould. Anything else is an error.
string.format("%05.1f|%-4s|%x", 3.14159, "ab", 255) --> "003.1|ab |ff"
string.format("%d-%d-%d-%d-%d", 1, 2, 3, 4, 5) --> "1-2-3-4-5"table: queries and slices: insert(t [, pos], v) (appends, or inserts at pos and
moves later elements up); remove(t [, pos]) (removes the last element, or the one at
pos, moving the rest down, and returns it; a pos out of range is an
invalidArgument error); concat(t [, sep]); keys(t), values(t) and items(t)
(arrays in pairs order; items gives {key = k, value = v} records, and values
holds the same tables rather than copies); indexof(t, v) (the position in the array
part, or nil); contains(t, v) (anywhere in the table); has(t, k) (the key has a
non-nil value; false counts as present); size(t) (all entries, where #t counts
only the array part); isempty(t); slice(t, i [, j]) (Lua's index rules);
reverse(t) (a new, reversed array); take(t, n) and drop(t, n) (split the array
part by count; counts below zero count as zero); append(t, v1 [, …v4]) (adds to the
array part; nil arguments are skipped); clear(t) (removes every entry in place); and
flatten(t) (one level; every element must be a table).
local list = { "a", "b", "c", "d" }
table.slice(list, 2, 3) --> {"b", "c"}
table.indexof(list, "c") --> 3
table.take(list, 2) --> {"a", "b"}
table.size({ 1, 2, x = 3 }) --> 3
table.flatten({ { 1, 2 }, { 3 } }) --> {1, 2, 3}table: copying and merging: clone(t) (a shallow copy of the table's own entries;
metatables aren't copied); deepcopy(t) (copies all the way down; shared tables and
loops are kept, metatables aren't copied); merge(a, b) (a new table, where b's
entries win); extend(dst, src) (copies src into dst and returns dst); and
defaults(t, d) (fills in only the keys that are nil in t; an existing false
stays).
table.merge({ a = 1, b = 2 }, { b = 3 }) --> {a = 1, b = 3}
table.defaults({ a = false }, { a = 1, b = 2 }) --> {a = false, b = 2}table: functions that take a callback work on the array part, in order. Your
callback runs as ordinary script code, with the usual limits and error rules, and
receives (value, index); you can leave out parameters you don't need, so
function(v) works everywhere, and so does passing a built-in such as tostring
directly. map(t, f) and collect(t, f) (two names, one
operation); filter(t, f); find(t, test) and findindex(t, test) (a function is
used as a test, and anything else is compared for equality; nil when absent);
reduce(t, f, initial) (combines left to right; f receives (acc, value, index));
each(t, f); any(t, test) and all(t, test); count(t [, test]) (the length, or the
number that pass); partition(t, test) (returns one table, with the passing
elements at [1] and the rest at [2]); group_by(t, keyfn) (a map of arrays: keys in
the order first seen, each group in input order); tomap(t, keyfn, valuefn) (later
elements win a key clash); unique(t) and unique_by(t, keyfn) (the first occurrence
wins, order kept); and sort(t [, less]), which sorts t in place and returns
nothing, as Lua's does,
while sorted(t [, less]) and sort_by(t, keyfn [, less]) return a new sorted
array. All three are stable: equal elements keep their order. Without a comparison
function, the elements must be all numbers or all strings (a mix is an error); a
comparison function receives (a, b) (the derived keys, for sort_by) and returns true
when a comes first. A callback that itself calls one of these functions can nest only
so deep: very deep nesting is a callDepthExceeded error.
local nums = { 5, 3, 8, 1 }
table.map(nums, function(v) return v * 2 end) --> {10, 6, 16, 2}
table.filter(nums, function(v) return v > 2 end) --> {5, 3, 8}
table.reduce(nums, function(acc, v) return acc + v end, 0) --> 17
table.sorted(nums) --> {1, 3, 5, 8}
nums --> {5, 3, 8, 1}
table.partition(nums, function(v) return v % 2 == 1 end) --> {{5, 3, 1}, {8}}
table.map({ 1, 2 }, tostring) --> {"1", "2"}
table.sort(nums)
nums --> {1, 3, 5, 8}
local people = { { name = "Ada", team = "x" }, { name = "Bo", team = "y" }, { name = "Cy", team = "x" } }
local byTeam = table.group_by(people, function(p) return p.team end)
#byTeam.x --> 2
table.sort_by(people, function(p) return p.name end)[1].name --> "Ada"set: new(list) (duplicates collapse), has(s, v), add(s, v) and remove(s, v)
(change the set and return it), union(a, b), intersection(a, b) and
difference(a, b) (new sets), and tolist(s) (members in the order first added). A set
is a plain table mapping each member to true, and members can be any valid table key.
local seen = set.new({ "a", "b", "a" })
set.has(seen, "a") --> true
set.tolist(set.union(seen, set.new({ "c" }))) --> {"a", "b", "c"}Handy globals: default(v, fallback) (the fallback only when v is nil; false
passes through); coalesce(a [, …d]) (the first non-nil of up to 4); pipe(x, f1 [, …f4]) (applies the functions left to right; with none it returns x);
assertf(cond, fmt [, …3 values]) (assert with a string.format message, built only
when it fails); and typecheck(v, expected [, name]) (an error you can catch, naming the
problem, or returns v).
default(nil, 5) --> 5
default(false, 5) --> false
coalesce(nil, nil, "third") --> "third"
pipe(3, function(x) return x + 1 end, function(x) return x * 10 end) --> 40time gives instants and durations as values that can't be changed: each method
returns a new value, so calls chain. Only fixed offsets from UTC are supported (no
named time zones or daylight saving). Create an instant with
time.new({year=, month=, day=, hour=, minute=, second=, millis=, offset=}) (the
parentheses are required; missing parts take defaults and an impossible date is an
error), time.fromepoch(ms [, offsetMinutes]) or time.parse(isoString) (ISO 8601).
Durations come from time.period({days=, hours=, minutes=, seconds=, millis=}) or
time.millis, seconds, minutes, hours and days(n).
Instant methods: :epoch_millis(), :offset(), :year(), :month(), :day(),
:hour(), :minute(), :second(), :add(p) and :subtract(p) (giving an instant),
:diff(other) (giving a duration), :before, :after and :equals(other),
:start_of_minute, _hour, _day, _month and _year(), :to_offset(minutes),
:with({…}) and :format([fmt]) (the %Y %m %d %H %M %S %z %% codes; with no
format, ISO 8601). Duration methods: :millis(), :add(p) and :negate().
time.now() gives the time of the run.
local start = time.parse("2026-03-30T09:15:00Z")
start:add(time.days(3)):format("%Y-%m-%d") --> "2026-04-02"
start:start_of_month():format() --> "2026-03-01T00:00:00Z"
time.parse("2026-03-31T00:00:00Z"):diff(start):millis() --> 53100000
start:to_offset(60):hour() --> 10uuid: uuid.parse(s) (the canonical lowercase form, or nil), uuid.is_valid(s),
uuid.version(s) and uuid.nil_uuid() work on existing UUIDs. uuid.v4() creates a
random one, and uuid.v7() one that also includes the time, so they sort by when they
were made.
uuid.parse("0190A5C8-8C3E-7B4A-9F21-3D6C2A1B0E9F") --> "0190a5c8-8c3e-7b4a-9f21-3d6c2a1b0e9f"
uuid.version("0190a5c8-8c3e-7b4a-9f21-3d6c2a1b0e9f") --> 7
uuid.is_valid("not-a-uuid") --> falseThe extra libraries (json, base64, hex, url, csv, decimal, stats,
template, bit32, hash, tpath, validate and text) are available in every
script; see Extra libraries.
Not present: io, os, debug, package and coroutine; load, loadstring and
dofile; next, collectgarbage, _G, getfenv and setfenv; math.random and
string.gmatch; print; goto; and first-class iterators of any kind. Load other
scripts with ctx.script.load. The bitwise operators & | ~ << >> don't
exist: they are syntax errors, found before the script runs. Use the bit32 extra
library instead.
Some things are deliberately missing:
| Item | Why |
|---|---|
iter.* (lazy iterators) |
pairs and ipairs are part of the loop syntax (Tables), so first-class iterators don't fit. Use the table functions that take a callback. |
fun.identity, constant, partial, compose, noop |
Each is a one-line Lua function; pipe covers composition. |
string.escape_pattern |
Not yet provided. |
class(base) |
It would need __call, which is refused. The class pattern in Tables does the job. |
serialize(value) |
Not yet provided: inspect is for people to read, not for loading back. |
module.new |
A module is a plain table and needs no helper (Loading other scripts). |
require_optional(name) |
Use pcall(function() return require(name) end): a missing module is an error you can catch. |
reload(name) |
Modules load once per run by design, and nothing is kept between runs to reload (Loading other scripts). |
path.* |
Not yet provided. |
| A bytes type | Binary data stays with CoCoCo, as objects (Objects from CoCoCo), and ctx functions work on it. Strings are always text. |