On this page

Scripting

Getting started

This is a gentle, hands-on introduction to writing SwiftLua scripts. You don't need to know Lua. If you've written a little JavaScript or TypeScript, you already know most of the ideas, and this guide points out the few differences as it goes. When you want the precise rules for anything here, the Language Guide is the full reference.

In the examples, --> shows what a line produces:

LUA
local answer = 6 * 7
answer  --> 42

What you're writing

A script is a small program that runs inside CoCoCo, safely. CoCoCo gives your script some input, your script works something out, and it hands back a result with return. A script reaches databases, devices and other services only through the ctx functions CoCoCo provides, and it always finishes, because every run has time and memory limits.

Think of a script as a function CoCoCo calls: input in, a value out.

If you've written JavaScript or TypeScript

Most of your instincts carry over:

You know (JS/TS) In SwiftLua
let x = 1 / const x = 1 local x = 1 (always local; there's no var)
// comment -- comment
=== / !== == / ~= (note: ~=, not !=)
&& / || / ! and / or / not
a + b to join strings a .. b (.. joins; + is for numbers only)
null / undefined nil (just one)
obj.field, arr[0] obj.field, arr[1] (arrays start at 1)
objects {} and arrays [] both are tables {} (one type, two uses)
x: number, "a" | "b", T | null x: number, "a" | "b", T?: TypeScript-style types, checked before the script runs
try { } catch { } pcall(...) (covered below)

The differences that trip people up are collected in the cheat-sheet at the end. Skim it once and you'll avoid the common surprises.

Your first script

Say a workflow script node receives an order as its input and should return the total price, with a 10% discount once the subtotal passes 100. Here's the whole thing:

LUA
local subtotal = 0
for _, line in ipairs(input.lines) do
  subtotal = subtotal + line.qty * line.price
end

local discount = 0
if subtotal > 100 then
  discount = subtotal * 0.1
end

return subtotal - discount

For an order of two items at 40 and one at 35, it returns 103.5. Line by line:

  • input is the order CoCoCo passed in; you just use it.
  • ipairs(input.lines) loops over the array input.lines in order. _ is the position (not needed here) and line is each element.
  • local makes a variable, and = assigns to it.
  • return hands your result back to CoCoCo, which passes it to the next node.

That's a real script. Everything below is more building blocks.

The building blocks

Variables

LUA
local total = 0
local name, qty = "widget", 3   -- declare several at once
total = total + 1               -- assign (there is no ++ or +=)
total  --> 1

Always use local. Assigning to a name you never declared (total = 1 with no local) creates a global, which the checker reports as an error, because it's almost always a typo. Reading a name that doesn't exist is an error too, where JavaScript would quietly give you undefined.

Numbers and strings

LUA
local n = 10
local r = 10 / 4
r  --> 2.5
local s = "qty=" .. n
s  --> "qty=10"

/ always gives a decimal result, and .. turns numbers into text for you. Integers and decimals are distinct, and integer arithmetic that overflows stops with an error instead of silently wrapping round. You'll rarely hit it, but it's why results can be trusted.

Tables: objects and arrays

A table is the only container. It's both your "object" and your "array":

LUA
local person = { name = "Ada", age = 36 }   -- like a JS object
person.name     --> "Ada"
person["age"]   --> 36

local items = { "a", "b", "c" }              -- like a JS array
items[1]        --> "a"
#items          --> 3

Arrays start at 1, not 0, and # gives the length. You can mix the two uses in one table, but typed code is clearer when arrays and records stay separate.

Conditionals and loops

LUA
local score = 85
local grade
if score > 90 then
  grade = "A"
elseif score > 80 then
  grade = "B"
else
  grade = "C"
end
grade  --> "B"

local sum = 0
for i = 1, 5 do sum = sum + i end          -- 1 through 5, inclusive
sum  --> 15

local letters = ""
for _, v in ipairs({ "x", "y", "z" }) do   -- each array element, in order
  letters = letters .. v
end
letters  --> "xyz"

local fields = 0
for key, value in pairs({ name = "Ada", age = 36 }) do   -- every key and value
  fields = fields + 1
end
fields  --> 2

Note that for i = 1, 5 includes 5: ranges include both ends.

Functions

LUA
local function area(w, h)
  return w * h
end

area(3, 4)  --> 12

A function can return more than one value. It's handy for "a result and an error", and reads like destructuring a tuple in TypeScript:

LUA
local function divmod(a, b)
  return a // b, a % b   -- // is whole-number division
end

local q, r = divmod(17, 5)  --> q = 3, r = 2

There are a few precise rules about multiple values (Functions and multiple returns), but the common case is exactly this.

Types: like TypeScript, checked before the script runs

You can annotate variables, parameters and return types, and a checker verifies them before the script runs, so typos and mismatched types are caught up front rather than halfway through.

LUA
local total: number = 0
local names: {string} = {}                   -- array of strings
local rates: {[string]: number} = { GBP = 1.25 }   -- map: string keys to numbers
local status: "open" | "closed" = "open"     -- only these two values allowed
local note: string? = nil                    -- optional: a string or nil

local function convert(amount: number, code: string): number
  return amount * (rates[code] or 1)
end

convert(10, "GBP")  --> 12.5

Unions, literal types, optionals (T?), arrays ({T}), maps ({[K]: V}) and function types ((number) -> number) are all there. You can name your own shapes too:

LUA
type Line  = { sku: string, qty: number }
type Order = { lines: {Line}, status: "open" | "closed" }

local function units(order: Order): number
  local count = 0
  for _, line in ipairs(order.lines) do count = count + line.qty end
  return count
end

units({ lines = { { sku = "A", qty = 2 }, { sku = "B", qty = 3 } }, status = "open" })  --> 5

The checker also narrows types as your code tests them, just like TypeScript:

LUA
local function describe(value: number | string): string | number
  if type(value) == "string" then
    return value .. "!"     -- here the checker knows value is a string
  else
    return value + 1        -- and here it's a number
  end
end

describe("hi")  --> "hi!"
describe(1)     --> 2

Types are optional: start without them and add them as you go. The checker is strict by default; putting --!nonstrict on the first line turns type findings into warnings while you're learning (Type checking).

Working with CoCoCo

Your script reaches the rest of CoCoCo only through what CoCoCo provides:

  • Input: the data your script was run with, like the order above. Where it comes from depends on where the script runs (Where scripts run).
  • ctx functions, grouped by area, such as ctx.graphql.query(…) or ctx.store.get("sync-state"). You call them like any other function. Most do real work (reading the database, calling a device) and wait briefly while they do; that happens by itself, with no special syntax (Calling CoCoCo).
  • Other scripts: ctx.script.load("helpers") loads one of your stored Scripts, usually a table of functions.
  • Your result: whatever you return.

A function can return a value and an error, which you read as a pair:

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 qty, err = parseQuantity("12")
qty  --> 12
err  --> nil

local bad, problem = parseQuantity("twelve")
bad      --> nil
problem  --> "not a quantity"

CoCoCo's own functions report problems in a similar way, as an ok flag and a result. See Calling CoCoCo.

When things go wrong

  • Errors stop the script: error("bad input"), a failed assert(condition, "message"), or a mistake at run time such as calling something that isn't a function. The run fails with a clear error, including the line it happened on.

  • Catching errors uses pcall, SwiftLua's try/catch:

    local function risky()
      error("out of stock", 0)
    end
    
    local ok, result = pcall(risky)
    ok      --> false
    result  --> "out of stock"
    
  • Limits: a script can't loop forever or use unlimited memory (Limits). If it reaches a limit, the run ends with an error saying which one, and pcall cannot catch it. That's deliberate: it keeps CoCoCo safe.

Gotchas cheat-sheet

The handful of things that surprise people coming from JavaScript:

  1. Arrays start at 1. items[1] is the first element; #items is the length.
  2. 0 and "" count as true. Only nil and false are false, so if 0 then runs.
  3. .. joins strings, not +. "a" + "b" is an error; "a" .. "b" is "ab".
  4. ~= means "not equal" (not !=), and it's and/or/not, not &&/||/!.
  5. No ++, += or var. Write x = x + 1, and always use local.
  6. Reading an unknown variable is an error, not undefined. That catches typos.
  7. nil is the only "empty". There's no separate null and undefined.
  8. One container type. {} is an object or an array depending on how you use it.
  9. Integer overflow is an error rather than wrapping round, so results stay correct.
  10. There's no print. return is how you give back a result, and ctx.log.info(…) writes to the run's log.

Where to go next

The Language Guide is the full reference. Useful places to jump to:

You don't need all of it to be productive. Come back when a specific question comes up. Happy scripting.