On this page

Scripting

Type checking

Type checking

Scripts are checked before they run. The checking mode goes on the first line:

  • --!strict (the default): unknown globals, unknown fields, wrong argument types or counts, and creating globals are errors. Local variables take their types from their first value, a local function's parameters from how they're used in arithmetic, and table literals are recognised as arrays or records.
  • --!nonstrict: those findings become warnings; outright contradictions (calling a number) are still errors. So are an unknown field on a record whose fields are all known, and an unknown global that the script never assigns and CoCoCo does not provide, because neither can exist at run time.
  • --!nocheck: no checking.
  • --!strict-nil: strict, and reading an array or map element gives an optional type, so check it (if v then …) or give a default (v or fallback) before using it. Declared record fields don't count, because they are a promise.
LUA
--!strict-nil
local prices: {number} = { 10, 20 }
return prices[5] + 1          -- reported: prices[5] may be nil
LUA
--!strict-nil
local prices: {number} = { 10, 20 }
return (prices[5] or 0) + 1   -- fine

Under --!nonstrict, softer findings (a wrong argument type, a global read before the script assigns it) are warnings rather than errors, which helps when adding types gradually, while real contradictions stay errors: calling a number, an unknown field on a known type, or a global the script never assigns and CoCoCo does not provide (such as os.time()), because that read can only fail when it runs.

--!doc comments. A --!doc <description> line describes what code is for, for the people and tools that read it. In a module, a --!doc at the top describes the module, and one (or several lines of them, which join up) just above an exported function or field (function M.fn() or M.fn = …) describes that function or field. It has no effect when the script runs.

Type annotations. Local variables, parameters and return values can be annotated. This is a SwiftLua addition to Lua's syntax:

LUA
local total: number = 0
local names: {string} = {}
local maybe: integer? = nil
local rates: {[string]: number} = { GBP = 1.25 }
local function apply(amount: number, code: string): number
  return amount * rates[code]
end
apply(8, "GBP")  --> 10

The type forms are: a name, T? (optional), {T} (array), {[K]: V} (map), {} (the empty record), A | B (either), (T, …) -> R (function), (T) (grouping) and literal types ("active", 42, true, nil), combined freely. A function may return several values ((T) -> (A, B), () -> (), function f(): (A, B)), checked one by one:

LUA
type Status = "active" | "archived" | "deleted"
local id: integer | string = 1
local s: "active" | "archived" = "active"
local lookup: {[string]: number} = {}
local maybe: Status | nil = nil          -- the same as Status?
local double: (number) -> number = function(x) return x * 2 end
local callback: ((number) -> number)? = nil   -- grouping for an optional function
local function minmax(xs: {number}): (number, number)
  return math.min(xs[1], xs[2]), math.max(xs[1], xs[2])
end
double(21)  --> 42
local lo, hi = minmax({ 9, 4 })  --> lo = 4, hi = 9

Names other than the built-in ones are types you declare (like Status above, with type) or types CoCoCo provides, such as Device or Time. The | and -> symbols exist only inside annotations; they aren't operators. -> binds loosest: (number) -> string | nil is a function returning string | nil.

Naming your own types. Name a shape with type, including records:

LUA
type Line = { sku: string, qty: number }
type Order = { lines: {Line}, status: "open" | "closed" }
type Node = { value: number, next: Node? }     -- a type can refer to itself

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

local chain: Node = { value = 1, next = { value = 2 } }   -- optional fields can be left out
total({ lines = { { sku = "A", qty = 4 } }, status = "closed" })  --> 4

A record can leave out its optional fields: a missing key is nil, and writing k = nil stores nothing, so the two are the same.

A type name applies to the whole file from where it's declared and only affects checking: the statement does nothing when the script runs. type is still the ordinary function (type(x)); only the exact form type Name = … declares a type. Declaring a name twice, or reusing the name of a type CoCoCo provides (such as Device), is an error: CoCoCo's names come first.

Casts. expr :: T tells the checker a type it can't work out itself:

LUA
type Order = { lines: {any}, status: "open" | "closed" }
local order = json.decode(input.payload) :: Order   -- you know the shape; the checker doesn't
order.status  --> "open"
local x: any = 2
1 + x :: number                               --> 3

:: binds tightly: 1 + x :: number casts x, not the sum. A cast between unrelated types (5 :: string) is an error: casts move between related types, they don't jump. Casts only affect checking. When the script runs, the value is whatever it really is, and every run-time rule and limit still applies, whatever a cast claims.

A cast is not a call: f() :: T in the last position gives one value. It does not fill the remaining variables or return values the way a bare f() would (see the rules in Functions and multiple returns). An annotation is a promise: it takes priority over what the checker would work out, values assigned must fit it, annotated parameters type the function body and every call, and a return annotation applies to every return. Annotations only affect checking.

CoCoCo's names are typed. Everything CoCoCo provides carries its real type into checking. ctx functions are checked against their declared parameters, however deeply the names are grouped: CoCoCo declares ctx.store.get(name: string), so ctx.store.get(42) is reported. Data with a known shape is typed by it (with a config value that has a field retries, config.retires is reported as an unknown field, including in nested tables and array elements). Objects and the Scripts you load bring their types too, as described in Loading other scripts and Objects from CoCoCo. Some values are deliberately typed loosely, because their shape varies from run to run: an input whose shape depends on the workflow is any, for example. Some functions are generic: a function declared as pick(items: {T}, chooser: (T) -> boolean): T gives a result typed by what you passed, and the chooser's parameter takes its type from the elements, exactly like the built-in table functions.

LUA
local ok, record = ctx.store.get(42)   -- reported: the name must be a string

Sets of allowed values. A union of literal types lists the values a string may take. Declare it once with type and use the name wherever that set of values belongs:

LUA
type Status = "active" | "archived" | "deleted"
local s: Status = "active"
s  --> "active"
s = "archived"                      -- fine
LUA
type Status = "active" | "archived" | "deleted"
local s: Status = "activ"           -- reported, listing the allowed values

Assigning anything that isn't one of the values is an error, including a plain string variable. A local with no annotation, set from a literal (local x = "active"), is a plain string, so annotate it to keep the narrower type.

Growing a table. A local that starts as a table literal gains fields as you add them, so the usual way of building a table is fully typed:

LUA
local cfg = {}            -- an empty record
cfg.retries = 3           -- cfg now has retries: number
cfg.label = "prod"        -- and label: string
cfg.retries  --> 3
LUA
local cfg = {}
cfg.retries = 3
return cfg.retires        -- reported: an unknown field (a typo caught)
LUA
local function newJob(name: string)
  local job = { name = name, id = nil }   -- id declared here, for later
  job.dueAt = "tomorrow"                  -- still being built: the field is added
  return job
end
local job = newJob("print")               -- fixed from here on
job.id = "job-1"                          -- fine: id was declared
job.id  --> "job-1"

Writing a new field adds it; reading a field that isn't there is an error; and writing an existing field must fit its type (m.weight = "heavy" into a number field is an error). A declared type is enforced strictly; a type the checker worked out allows widening between numbers, nil, and changes of table shape, just as a local can be reassigned. Everywhere else the shape is fixed: an annotation is a promise (local p: Point doesn't grow), a second name for the table (local u = t) sees the shape at that point, and a function sees the table as it was when it was called, so a table returned from a function is fixed for the caller. To fill a field in later, include it when the table is built (id = nil, which lets the field hold any type) or annotate it with a type that has an optional field; the error on the write says so. Array literals stay arrays: a table mixing an array and fields needs a declared record or map type.

A record or array literal can still be used where a map type is expected: a record {a = 1, b = 2} fits {[string]: number}, and an array {1, 2, 3} fits {[integer]: number} (each field or element must fit the map's value type). So table.merge({a = 1}, {b = 2}) and other functions that take maps check with plain literals.

Typed standard library. The table functions that take callbacks are fully typed: the callback's (value, index) parameters take their type from the elements (so table.map(flags, function(v) return v + 1 end) is an error when flags is {boolean}), results have real element types (map returns an array of what the callback returns, filter and sort keep the input's element type, and find returns an optional element, so check it), reduce carries the accumulator's type from its starting value, and group_by and tomap build typed maps. Loop variables take their type from the elements too: for _, v in ipairs(xs) gives v the element type of xs. pcall(f, …) gives (boolean, R | string) where R is what f returns, so check with type(v) before using it as R when R could itself be a string.

Narrowing. The checker follows your code. A condition refines types in the branches it guards, and the refinement holds through the shapes Lua code really uses:

LUA
local function describe(value: integer | string): string | integer
  if type(value) == "string" then     -- value is a string here
    return value .. "!"
  else
    return value + 1                  -- and an integer here
  end
end
describe("hi")  --> "hi!"

local function bump(maybe: number?): number
  if maybe == nil then return 0 end   -- an early return
  return maybe + 1                    -- maybe is not nil from here on
end
bump(nil)  --> 0

local function add(first: number?, second: number?): number
  if first ~= nil and second ~= nil then   -- both are narrowed
    return first + second
  end
  return 0
end
add(2, 3)  --> 5

type Message = { kind: "add", amount: number } | { kind: "note", text: string }
local function handle(msg: Message): number | string
  if msg.kind == "add" then           -- testing a shared literal field
    return msg.amount                 -- picks the matching record shape
  else
    return msg.text                   -- and the other branch gets the rest
  end
end
handle({ kind = "add", amount = 4 })  --> 4

The forms it recognises: truthiness (x, not x); comparisons with nil; type(x) == "kind" (including "table" and "function"); equality with a literal or enum value (an integer literal works against a number: 401 == 401.0); and and or (the right-hand side knows what the left-hand side established, so if errors and #errors > 0 works); and if <cond> then return/error end guards (whose opposite holds for the rest of the block). Field paths (a.b.c) narrow; call results and t[k] don't, so put them in a local first. The right-hand side of or knows the left-hand side was false, so if res == nil or res.status ~= 401 then works too. Assigning to a narrowed variable ends the narrowing: the assignment is checked against the variable's declared type, and the narrowed view follows the new value. A field that exists on only some members of a union is an error until you narrow, and indexing a value that might not be a table (a pcall result, say) is an error until you check it. That's the checker telling you which check to write.

pcall pairs. local ok, v = pcall(f) links the two: if ok then narrows v to what f returns, and the other branch (or an if not ok then return end guard) narrows v to the error message string. Assigning to either variable unlinks them.

Covering every case. Branches understand which values of a literal union they cover, cumulatively: each elseif and the else know which values earlier branches took:

LUA
type Status = "active" | "archived" | "deleted"
local function label(s: Status): string
  if s == "active" then
    return "live"
  elseif s == "archived" then
    return "kept"
  else
    return "gone: " .. s        -- s can only be "deleted" here, and the checker knows it
  end
end
label("deleted")  --> "gone: deleted"

A branch that can never run (a repeated case, an impossible type test) gets a warning, and an if/elseif chain on a literal union with no else and missing values gets a warning naming the missing values. Both are only ever warnings: add the branch or an else to clear them. Once every value is covered, a defensive else is still allowed and raises nothing.

The checker helps you get things right early; the rules are enforced when the script runs regardless.