> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreflux.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Types and Methods

> How LoT reads a missing value, checks a type, and works with text, numbers, timestamps, arrays, JSON members, and connector status.

## Know the value first

An action often reads a topic that has never been written, a JSON field the device left out, or a list of readings to walk one by one. The type of that value decides whether the next line adds a number, formats a time, or stops the action.

> [!TIP]
>
> **Like a form with a blank box.** An empty box is not the number zero. You notice the blank first, then you decide what to write in it.

## When to use this

| You want to | Use |
| - | - |
| Survive the first run of a counter | `EQUALS EMPTY`, then cast |
| Tell a whole number from text | `IS INT`, `IS STRING`, and the other `IS` checks |
| Clean, split, or search text | A string method such as `.SPLIT` |
| Round, clamp, or take an absolute value | A number method such as `.ABS` |
| Work with angles, or the larger of two values | `.SIN` / `.COS`, `ATAN2(y, x)`, `MIN(a, b)`, `MAX(a, b)` |
| Format or shift a UTC timestamp | `TIMESTAMP.NOW.UTC` and `.FORMAT` / `.ADD` |
| Hold several values and test membership | `ARRAY` and `IN` |
| Read a JSON field, or list an object's keys | `PAYLOAD.temperature`, `report.KEYS` |
| Ask whether a connector is up | `Name.CONNECTED` |

***

The examples below are full actions. Loops, `TRY`, and triggers are on [Operations](https://docs.coreflux.org/latest/lot-language/actions/operations.md#control-flow) and [Action Triggers](https://docs.coreflux.org/latest/lot-language/actions/events.md).

## Quick start

> [tab] First-run counter
>
> A missing topic is NULL. Check it before you cast, then store the next count:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE ACTION NextCount
> ON TOPIC "demo/tick" DO
>     IF GET TOPIC "counter" EQUALS EMPTY THEN
>         SET "n" WITH 1
>     ELSE
>         SET "n" WITH (GET TOPIC "counter" AS INT) + 1
>     KEEP TOPIC "counter" WITH {n}
>     PUBLISH TOPIC "stats/count" WITH {n}
> ```

> [tab] Walk a list
>
> Build an array, then publish each value. `FOR` binds each element in turn:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE ACTION PublishReadings
> ON TOPIC "demo/readings" DO
>     SET nums AS ARRAY OF INT = [10, 20, 30]
>     FOR n IN {nums}
>         PUBLISH TOPIC "demo/item" WITH {n}
> ```

> [tab] Format a time
>
> Take the current UTC time and publish a calendar day:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE ACTION StampDay
> ON TOPIC "demo/stamp" DO
>     SET "now" WITH TIMESTAMP.NOW.UTC
>     PUBLISH TOPIC "time/iso" WITH {now}
>     PUBLISH TOPIC "time/day" WITH {now}.FORMAT("yyyy-MM-dd")
> ```

## Empty values

> [!WARNING]
>
> A missing read is LoT NULL. It is not the text `"null"`. Whether `AS INT`, `AS DOUBLE`, and `AS BOOL` raise on it depends on where the cast is written. Outside `TRY` those casts become `0` or `false`, as on broker 2.22: an action that did `GET TOPIC "counter" AS INT` on the first run, before any value was stored, gets `0`. Inside a `TRY` body, or in an action that has `ON ERROR`, the same cast raises. See [Casts inside TRY](#casts-inside-try).

These reads are NULL when the value is not there:

* `GET TOPIC` when nothing has been kept, cached, or retained on that topic
* `GET ENV` or `GET SECRET` when that name is unset
* `GET JSON` or a member such as `PAYLOAD.temperature` when the key is missing
* `GET PROTO` with no cast when the field is absent

`EQUALS EMPTY` and `== EMPTY` are the blank check. They match NULL and a present empty string `""`. They do not match a string that is only spaces. `EQUALS null` and `EQUALS NULL` match NULL only, not `""`.

A secret that exists but cannot be decrypted, or that has an invalid stored format, reads as an empty string. `EQUALS EMPTY` matches that empty string and a missing `GET ENV` or `GET SECRET`.

`AS INT`, `AS DOUBLE`, and `AS BOOL` in this table apply to `GET TOPIC`, `PAYLOAD`, `GET JSON`, a member read, `GET ENV`, `GET SECRET`, and `SET "n" WITH {raw} AS …`.

| Cast or operator on NULL | Result |
| - | - |
| No cast | NULL |
| `AS STRING` | `""` |
| `AS INT`, `AS DOUBLE`, `AS BOOL` | Runtime error inside `TRY` or an action with `ON ERROR`. Elsewhere `AS INT` and `AS DOUBLE` are `0` and `AS BOOL` is `false` |
| `AS TIMESTAMP` | Runtime error |
| Arithmetic, or unary `NOT` | Runtime error |

### Casts inside TRY

`TRY` decides whether a cast raises. The raising scope is code written inside a `TRY` body, and the body of an action that has `ON ERROR` (that body runs as an implicit `TRY` whose `CATCH` is the handler). A `CATCH` body and an `ON ERROR` handler are outside it. The rule is lexical: an action started with `CALL ACTION` does not inherit the caller's `TRY`, so its casts raise only inside its own `TRY` or `ON ERROR`. An error it raises still reaches the caller's `TRY`. Model `ON ERROR` bodies keep lenient casts.

| Cast | Outside the raising scope | Inside `TRY` or an action with `ON ERROR` |
| - | - | - |
| `AS INT`, `AS DOUBLE` on NULL, `""`, or text that is not a number | `0` / `0.0` | Raises `NULL cannot be converted AS INT`, `Cannot convert '' to INT` or `Cannot convert 'abc' to INT` (or `DOUBLE`) |
| `AS INT` outside -2147483648 to 2147483647 | `0` | Raises `Cannot convert '3000000000' to INT` |
| `AS BOOL` | `true`, `yes`, `on` (any case) and any non-zero number are `true`; everything else is `false` | Accepts only `true`, `false`, `1` or `0` (any case, trimmed). Other text raises `Cannot convert 'yes' to BOOL`; NULL raises `NULL cannot be converted AS BOOL` |
| Typed `GET ENV` / `GET SECRET`, unset or not convertible | `0`, `0.0`, `false` or `""` | Raises |
| A failed `CALL PYTHON` | Logged; the `RETURN` variable is NULL | Raises `CALL PYTHON ScriptName.function failed: …` |

These rules apply to `GET TOPIC`, `PAYLOAD`, `GET JSON`, a member read, `GET ENV`, `GET SECRET`, and `SET "n" WITH {raw} AS INT`, `AS DOUBLE`, or `AS BOOL`. `GET ENV` and `GET SECRET` are trimmed before the cast.

A present numeric string parses. `"42"` is 42, and `"1e3"` is 1000. Fractions truncate toward zero everywhere, inside or outside `TRY`: `"3.9" AS INT` and `3.9 AS INT` are `3`, and `-3.9` is `-3`. Only text that is not a number, such as `"abc"`, is a failure.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION ReadLevel
ON TOPIC "tank/level" DO
    SET "soft" WITH PAYLOAD AS INT
    TRY
        SET "level" WITH PAYLOAD AS INT
        PUBLISH TOPIC "tank/level/ok" WITH {level}
    CATCH
        PUBLISH TOPIC "tank/level/bad" WITH ERROR.MESSAGE
```

A payload of `abc` sets `soft` to `0`, and the cast inside `TRY` raises `Cannot convert 'abc' to INT`, so `CATCH` publishes the message.

Arithmetic raises whether or not it is inside `TRY`. `-`, `*`, `/`, `%`, a number method, or `+` with a number on text that is not a number raises `Cannot use 'abc' in math: not a number`. That includes `""` and `1,5`. That text used to count as 0. NULL in arithmetic raises `NULL used in math`.

`+` joins text when either side is typed as text: a string literal, a text variable, an `AS STRING` cast, or a string method result. `"Total: " + {n}` joins, and so does `PAYLOAD + "1"`, which gives `41` for a payload of `4`. An untyped value next to a number adds: `PAYLOAD + 1` gives `5` for `4` and raises for `abc`. Two untyped values, such as `PAYLOAD + GET TOPIC "t"`, join as text. Cast with `AS DOUBLE` or `AS STRING` when you want to be sure.

[String interpolation](https://docs.coreflux.org/latest/lot-language/actions/operations.md#string-interpolation) follows the same rule as a string literal next to `+`: `"Total: ${n}"` gives the same text as `"Total: " + {n}`, and `"${a}${b}"` joins two numbers as text.

Comparisons such as `<` and `==` are not casts and stay lenient: text that is not a number compares as 0, and the comparison does not raise. A comma does not make the text numeric. `"1,5" > 0` is false, the same as `"abc" > 0`.

In LoT source, `.` is the only decimal separator. Write `2.5`, not `2,5`. A comma between digits is a list separator (`{t}.CLAMP(0,100)`, `[1,2,3]`). The parse error says to `write 2.5, not 2,5`. Route `SCALING` and `DEADBAND` values with a comma are refused the same way. A comma is never numeric in text the action reads either. `"1,5"` compares like `"abc"`. A soft typed `GET TOPIC` read gives null. A protobuf numeric cast gives 0. A cast inside `TRY` raises, and math raises `Cannot use '1,5' in math: not a number`.

`INT` is a 32-bit whole number, from -2147483648 to 2147483647. Whole-number arithmetic that overflows raises `Arithmetic operation resulted in an overflow.` (`ERROR.CODE` `OverflowException`) instead of wrapping around, inside or outside `TRY`. `AS INT` on a value outside that range raises inside `TRY`, for example `Cannot convert '3000000000' to INT`, and gives 0 elsewhere. `TIMESTAMP.NOW.UNIX` and `.TO.INT` are 64-bit. See [Dates and times](#dates-and-times).

`TRUE AS INT` is 1 and `FALSE AS INT` is 0. `AS DOUBLE` gives 1.0 and 0.0. This applies to LoT boolean values. A member read returns text, so `PAYLOAD.flag AS INT` on a JSON `true` raises inside `TRY`.

Protobuf field casts are the one exception in this release. A missing protobuf field reads as the field's default, so it gives 0 under `AS INT` and `AS DOUBLE` and false under `AS BOOL`. `AS BOOL` accepts `true`, `1`, `yes`, and `on`, and `false`, `0`, `no`, and `off`. Letter case does not matter. A blank string gives false. A nonzero number gives true, and other text gives false without an error. Text that is not a number gives 0 under `AS INT` and `AS DOUBLE`. Text with a comma, such as `1,5`, is not a number, so those casts give 0. See [GET PROTO](https://docs.coreflux.org/latest/lot-language/actions/operations.md#get-proto).

### Guard before you cast

Guard a cast with `IS INT` or `IS DOUBLE`, check `EQUALS EMPTY` first, or wrap it in `TRY` when the error should be handled. A guarded cast behaves the same inside and outside `TRY`. See [Type checks](#type-checks) and [TRY and CATCH](https://docs.coreflux.org/latest/lot-language/actions/operations.md#try-and-catch).

Check for a blank, then cast. You can also seed the topic with a visible `KEEP TOPIC "counter" WITH 0` before any action reads it:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION CountAfter
ON TOPIC "demo/tick" DO
    IF GET TOPIC "counter" EQUALS EMPTY THEN
        SET "n" WITH 1
    ELSE
        SET "n" WITH (GET TOPIC "counter" AS INT) + 1
    KEEP TOPIC "counter" WITH {n}
```

Read the topic with no cast, then cast the variable. A missing topic and an empty string take the default. Inside `TRY`, a topic holding `abc` still raises `Cannot convert 'abc' to INT` in the other branch:

```lot wrap focus={3-7} theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION GuardedCast
ON TOPIC "demo/tick" DO
    SET "raw" WITH GET TOPIC "counter"
    IF {raw} EQUALS EMPTY THEN
        SET "n" WITH 0
    ELSE
        SET "n" WITH {raw} AS INT
    KEEP TOPIC "counter" WITH {n}
```

`NOT` negates a boolean. A text operand must be `true`, `false`, `1`, or `0`. `NOT` on NULL, on `""`, or on other text raises. Inside an `IF` condition, the words `yes` and `on` still count as true. `NOT` does not use that reading.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION StoppedFlag
ON TOPIC "machine/running" DO
    SET "running" WITH PAYLOAD AS BOOL
    SET "stopped" WITH NOT {running}
    PUBLISH TOPIC "machine/stopped" WITH {stopped}
    IF NOT {running} THEN
        PUBLISH TOPIC "alerts/machine" WITH "machine stopped"
```

A payload of `false` sets `stopped` to true and sends the alert. `NOT {a} == {b}` means `NOT ({a} == {b})`.

## Type checks

`IS` tests the runtime type. A mismatch is false. The check does not raise.

| Check | Matches |
| - | - |
| `IS INT` | A whole number in the 32-bit range, or a 64-bit Unix time in milliseconds from `TIMESTAMP.NOW.UNIX` or `.TO.INT`. `"3000000000" IS INT` is false, and `IS DOUBLE` is true |
| `IS DOUBLE`, `IS FLOAT` | A fractional number |
| `IS BOOL` | `TRUE` or `FALSE` |
| `IS STRING` | Text |
| `IS OBJECT` | A JSON object |
| `IS ARRAY` | An array |
| `IS TIMESTAMP` | A timestamp inside the UTC window below |
| `IS BYTES` | Raw bytes |

A number is a timestamp under `IS TIMESTAMP` only when it is Unix milliseconds from `946684800000` through `4102444800000` (years 2000 through 2100 UTC). A number the size of Unix seconds is not a timestamp. `AS TIMESTAMP` reads any number as Unix milliseconds, with no window, so `5 AS TIMESTAMP` is `1970-01-01T00:00:00.005Z`. It accepts the same string forms as `IS TIMESTAMP`. NULL or an empty input raises. The string forms are under [Dates and times](#dates-and-times).

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION AcceptNumber
ON TOPIC "demo/value" DO
    IF PAYLOAD IS INT THEN
        PUBLISH TOPIC "demo/int" WITH PAYLOAD
    ELSE IF PAYLOAD IS DOUBLE THEN
        PUBLISH TOPIC "demo/double" WITH PAYLOAD
    ELSE
        PUBLISH TOPIC "demo/other" WITH "skipped"
```

## Text methods

String methods use uppercase names. A NULL receiver becomes `""`, so the method still runs. Call them on a braced variable, `PAYLOAD`, a string literal, a parenthesised expression, or the result of an earlier string or number method. A date part is a receiver too. A number part (`.YEAR`, `.MONTH`, `.DAY`, `.HOUR`, `.MINUTE`, `.SECOND`, `.DAY_OF_WEEK`, `.DAY_OF_YEAR`, `.TO.INT`) takes number methods, and a text part (`.FORMAT(…)`, `.TO.STRING`) takes string methods: `{ts}.FORMAT("dd/MM").REPLACE("/", "-")`. `{ts}.YEAR.UPPER` is refused when you deploy. A name the action has bound (a `SET` target, an `INPUT`, a `RETURN` name, or a `FOR` variable) is a receiver too: `report.UPPER` is `{report}.UPPER`. After a member, the method applies to the member: `PAYLOAD.name.UPPER`. Inside the explicit `.JSON.` form, a key with the same name wins, so wrap the value when you want the method: `(PAYLOAD.JSON.code).LENGTH`. See [Member access](#member-access).

| Method | Result |
| - | - |
| `.UPPER` / `.LOWER` | The text in upper or lower case |
| `.TRIM` | Leading and trailing spaces removed |
| `.LENGTH` | The number of characters |
| `.REPLACE(old, new)` | The text with every `old` replaced by `new`. An empty `old` raises |
| `.CONTAINS(text)` | True when the text contains `text` |
| `.STARTS_WITH(text)` / `.ENDS_WITH(text)` | True when the text starts or ends with `text` |
| `.SPLIT(separator)` | An `ARRAY OF STRING`, split on `separator` |
| `.SLICE(start, end)` | The characters from `start` up to, but not including, `end` |
| `.MATCH(regex)` | True when `regex` matches anywhere in the text |
| `.EXTRACT(regex)` | The first part of the text that `regex` matches, or `""` when nothing matches |

`.MATCH` and `.EXTRACT` use .NET regular expressions. An empty or invalid pattern raises, and so does a match that takes longer than 100 ms. Comparisons are case-sensitive.

`FILTER`, `REPLACE … IN`, and `SPLIT … CSV` on the [operations](https://docs.coreflux.org/latest/lot-language/actions/operations.md#string-transformations) page are separate statements. They still work.

Split a comma-separated payload and publish each piece. The loop variable holds the piece:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION SplitTags
ON TOPIC "demo/tags" DO
    SET "tags" WITH PAYLOAD.SPLIT(",")
    FOR t IN {tags}
        PUBLISH TOPIC "demo/tag" WITH {t}
```

## Number methods

Number methods use uppercase names and the same receivers as string methods. NULL raises. `.ROUND` rounds half away from zero. `.SIN`, `.COS`, and `.TAN` take radians, and `.ASIN`, `.ACOS`, and `.ATAN` give radians. The `_DEG` forms work in degrees.

`.ABS`, `.ROUND`, `.CEIL`, `.FLOOR`, and `.CLAMP` give an `INT` when the value is an `INT` (and, for `.CLAMP`, both bounds are too). Otherwise they give a decimal. A value whose type is known only when the action runs, such as `PAYLOAD.ABS` or an untyped `GET TOPIC`, counts as a decimal. `.SQRT`, `.POW`, `.LOG`, `.LOG10`, and the trigonometric methods always give a decimal. `.ABS` of -2147483648 raises, because the result does not fit in an `INT`.

| Method | Result |
| - | - |
| `.ABS` | The value with the sign removed |
| `.ROUND` / `.ROUND(n)` | Rounded to `n` decimal places, half away from zero. `.ROUND` is `.ROUND(0)`. A negative `n` rounds to tens, hundreds, and so on: `1250.ROUND(-2)` is 1300. An `INT` with `n` of 0 or more is returned unchanged |
| `.CEIL` / `.FLOOR` | The next or previous whole number |
| `.CLAMP(min, max)` | The value limited to `min` and `max`. A `min` above `max` raises |
| `.SQRT` | The square root |
| `.POW(n)` | The value raised to the power `n` |
| `.LOG` / `.LOG10` | The natural log, or the base-10 log |
| `.SIN` / `.COS` / `.TAN` | The sine, cosine, or tangent of an angle in radians |
| `.ASIN` / `.ACOS` / `.ATAN` | The inverse sine, cosine, or tangent, in radians |
| `.SIN_DEG` / `.COS_DEG` / `.TAN_DEG` | The same, for an angle in degrees |
| `.ASIN_DEG` / `.ACOS_DEG` / `.ATAN_DEG` | The inverse, in degrees |

Three math functions take arguments in parentheses instead of a receiver:

| Function | Result |
| - | - |
| `ATAN2(y, x)` | The angle of the point (x, y), in radians. `ATAN2_DEG(y, x)` gives degrees |
| `MIN(a, b, …)` / `MAX(a, b, …)` | The smallest or largest of two or more values. An `INT` when every argument is an `INT`, otherwise a decimal |

`ATAN2` takes exactly two arguments, and `MIN` and `MAX` take two or more. Other counts are refused when you deploy (`ATAN2 takes two arguments: ATAN2(y, x).`, `MIN takes two or more arguments`). The `_DEG` forms are exact at the usual angles: `180.SIN_DEG` is `0` and `1.ASIN_DEG` is `90`. `MIN OF TOPIC …` with no parentheses is still the [topic aggregate](https://docs.coreflux.org/latest/lot-language/actions/operations.md#topic-aggregates).

`.SQRT`, `.LOG`, and `.LOG10` of a negative number give not-a-number, and `.LOG` or `.LOG10` of 0 gives negative infinity. They do not raise. Dividing a fractional number by zero does not raise either. The result is an infinity or not-a-number value. `TRY` does not see it.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION ScaleAbsolute
ON TOPIC "demo/temp" DO
    SET "t" WITH PAYLOAD AS DOUBLE
    SET "scaled" WITH ({t}.ABS * 2)
    PUBLISH TOPIC "demo/scaled" WITH {scaled}
```

Turn an x/y vibration reading into a heading in degrees, and cap a setpoint.

A message on `sensors/vib`:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
{
  "x": 1,
  "y": 1,
  "requested": 120
}
```

`Heading` publishes a heading of `45` and a setpoint of `80`:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION Heading
ON TOPIC "sensors/vib" DO
    SET "heading" WITH ATAN2_DEG(PAYLOAD.y AS DOUBLE, PAYLOAD.x AS DOUBLE)
    SET "setpoint" WITH MIN(PAYLOAD.requested AS INT, 80)
    PUBLISH TOPIC "sensors/vib/heading" WITH {heading}
    PUBLISH TOPIC "sensors/vib/setpoint" WITH {setpoint}
```

## Dates and times

`TIMESTAMP "UTC"`, `TIMESTAMP "UNIX"` (seconds), and `TIMESTAMP "UNIX-MS"` are unchanged. The methods below always use UTC, and every number they read or give as a time is Unix milliseconds.

| Form | Result |
| - | - |
| `TIMESTAMP.NOW.UTC` | The string `yyyy-MM-ddTHH:mm:ss.fffZ` |
| `TIMESTAMP.NOW.UNIX` | Unix time as a 64-bit whole number of milliseconds |
| `TIMESTAMP.FROM(expr)` | The string `yyyy-MM-ddTHH:mm:ss.fffZ`, parsed from the expression |

`TIMESTAMP.FROM` accepts a strict ISO-8601 string, the exact form `yyyy-MM-dd HH:mm:ss`, or an ISO date-time with no offset. The form `yyyy-MM-dd HH:mm:ss` and an ISO date-time with no offset are read as UTC. A number, or text holding a whole number, is read as Unix milliseconds: `TIMESTAMP.FROM(1743503445000)` is `2025-04-01T10:30:45.000Z`. Whole-number text is tried as milliseconds before ISO. Text with a fraction or exponent, such as `"1.5e3"`, is not a time and raises. NULL, an empty string, spaces, or a malformed value raises.

`AS TIMESTAMP` accepts that same window and the same string forms as `IS TIMESTAMP`. NULL or an empty input raises.

Read a part of the timestamp with `.YEAR`, `.MONTH`, `.DAY`, `.HOUR`, `.MINUTE`, `.SECOND`, `.DAY_OF_WEEK`, or `.DAY_OF_YEAR`. Every part is an `INT`. `.DAY_OF_WEEK` is 1 for Monday through 7 for Sunday, in UTC. Call a number method on a part directly: `{now}.YEAR.ABS`, `{now}.DAY_OF_WEEK.CLAMP(1, 5)`. A string method on a part, such as `{now}.YEAR.UPPER`, is refused when you deploy.

`.FORMAT(pattern)` replaces these fields: `yyyy` (year), `yy` (year modulo 100), `MM` / `M` (month), `dd` / `d` (day), `HH` / `H` (hour, 0 to 23), `mm` / `m` (minute), `ss` / `s` (second), and `fff` (milliseconds). The two-letter fields are zero-padded and the single-letter ones are not. At each position the longest field is tried first. Every other character is kept as written, so `yyyy-MM-ddTHH:mm` keeps the `T`, and `YYYY` or `DD` is plain text. A field letter inside a word is still replaced: `Status` becomes `Statu` followed by the seconds. Put such text in single quotes: `'Status'` is copied without the quotes. Outside a quoted run, `''` is one quote. Inside a run, the first `'` ends it, so `'it''s'` gives `its`. A quote that never closes copies the rest of the pattern. No pattern raises, and `""` gives `""`. The pattern is not tied to a language or region.

`TIMESTAMP.NOW.UTC` gives `yyyy-MM-ddTHH:mm:ss.fffZ`. `TIMESTAMP.NOW.UNIX` gives a 64-bit whole number of milliseconds.

`.TO.STRING` and `.TO.INT` (Unix milliseconds) are the datetime conversions. `AS` is for other values: a datetime is ISO text, so inside `TRY` `{ts} AS INT` raises `Cannot convert '2025-04-01T10:30:45.000Z' to INT`, and elsewhere it gives 0. `.TO.INT` and `TIMESTAMP.NOW.UNIX` are 64-bit, and arithmetic on them stays 64-bit. `AS INT` on such a value is a 32-bit cast: a value outside the 32-bit range raises inside `TRY` and gives 0 elsewhere.

`.ADD(n UNIT)` and `.SUBTRACT(n UNIT)` accept `DAY` or `DAYS`, `HOUR` or `HOURS`, `MINUTE` or `MINUTES`, `SECOND` or `SECONDS`, `MILLISECOND` or `MILLISECONDS`, and `WEEK` or `WEEKS`. There is no month unit. `.TRUNCATE(UNIT)` accepts `DAY`, `HOUR`, `MINUTE`, or `SECOND`.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION PlanTomorrow
ON TOPIC "demo/plan" DO
    SET "now" WITH TIMESTAMP.NOW.UTC
    SET "fmt" WITH {now}.FORMAT("dd/MM/yyyy")
    SET "tomorrow" WITH {now}.ADD(1 DAYS)
    SET "hour_floor" WITH {now}.TRUNCATE(HOUR)
    SET "chained" WITH TIMESTAMP.FROM("2025-04-01T10:30:45Z").TRUNCATE(DAY).ADD(12 HOURS)
    PUBLISH TOPIC "time/tomorrow" WITH {tomorrow}
    PUBLISH TOPIC "time/label" WITH {fmt}
```

## Work with arrays

An array is an ordered list. Indexes start at 0. Build one with `SET name AS ARRAY`, optionally `OF` a single element type. The name is not quoted. `=` is allowed on that statement. A plain `SET "x" = [1, 2, 3]` does not define an array. Use `WITH` or `TO` for other assignments, or `AS ARRAY` when you write `=`.

`OF` accepts `INT`, `DOUBLE`, `FLOAT`, `DECIMAL`, `BOOL`, `STRING`, `OBJECT`, and `TIMESTAMP`. An array of arrays is not a type you can declare. Put an inner list in an `OBJECT` when you need nesting.

The element type is enforced when you build the array with `SET` and when you `.APPEND` to it, including `SET a TO {a}.APPEND(x)`. A mismatch raises a message such as `ARRAY OF INT 'tags': element [2] is STRING "x", not INT`. The index is the element's position, or the new length for `.APPEND`. A member index write such as `SET report.items[0] = …` is not checked. A plain `ARRAY` accepts any element.

| `OF` | Accepts |
| - | - |
| `DOUBLE` | Any number. A whole-number element is read back as a decimal |
| `INT` | Whole numbers, including `2.0`. `2.5` raises |
| `STRING`, `TIMESTAMP` | Text |
| `BOOL` | `TRUE` or `FALSE` |
| `OBJECT` | Objects |

NULL never matches an element type.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION BuildArrays
ON TOPIC "demo/build" DO
    SET readings AS ARRAY OF DOUBLE = [1.0, 2.5, 3.0]
    SET tags AS ARRAY OF STRING = ["a", "b"]
    SET empty AS ARRAY OF INT = []
    SET mixed AS ARRAY = [1, "x", TRUE]
    PUBLISH TOPIC "demo/first" WITH {readings}[0]
```

Methods use uppercase names. `.APPEND`, `.REMOVE_AT`, and `.SORT` return a new array. Assign it again with `SET` if you want to keep the result. On NULL, `.LENGTH` is 0, `.CONTAINS` and `.SLICE` treat it as `""`, and an array-only method raises, for example `FIRST on null is a runtime error.` An index outside the array raises `Array index N out of range.`

| Method | Result |
| - | - |
| `{arr}[n]` | The element at index `n` |
| `.FIRST` / `.LAST` | The first or last element |
| `.SLICE(start, end)` | A new array from `start` up to, but not including, `end` |
| `.LENGTH` | The number of elements |
| `.CONTAINS(v)` | True when `v` is an element |
| `.SUM` / `.AVERAGE` / `.MAX` / `.MIN` | The aggregate |
| `.APPEND(v)` | A new array with `v` added at the end |
| `.REMOVE_AT(n)` | A new array without the element at `n` |
| `.SORT(ASC)` / `.SORT(DESC)` | A new array in that order |

An empty array has `.LENGTH` 0 and `.CONTAINS` false.

* `.SUM` is always a decimal, so `{nums}.SUM IS INT` is false. An empty array sums to `0.0`. A NULL or non-numeric element raises `SUM requires numeric array elements.` To add the latest payload on many topics, use [`SUM OF TOPIC`](./operations#topic-aggregates).
* `.AVERAGE` is the sum divided by the count. An empty array raises `AVERAGE on empty array is a runtime error.` `.MAX` and `.MIN` raise the same way on an empty array.
* `.MAX` and `.MIN` compare two numbers as numbers and anything else as text, with NULL as `""`. On a mixed array the result depends on the order, so declare `ARRAY OF INT` or `ARRAY OF DOUBLE` when you need a numeric maximum.
* `.SORT` needs all numbers or all text, with no NULL. Otherwise it raises `SORT requires uniformly ordered elements (all numeric or all string).`
* `.SLICE` clamps `start` and `end` to the array. A `start` at or past `end` gives an empty array.
* An index, or a `.SLICE` or `.REMOVE_AT` argument, is read as a whole number: `{a}[1.7]` reads index 1.
* `.CONTAINS` and `IN` compare numbers as numbers, booleans as booleans, and anything else as text, so `1` and `"1"` are equal.

`<value> IN <array>` is the same test as `<array>.CONTAINS(<value>)`. When the right side is text and not an array, `IN` tests for a substring: `"ab" IN "xabc"` is true. This `IN` is not the `IN` in `GET JSON … IN PAYLOAD`, and it is not the `IN` on `FOR`.

`IN` binds like `<` and `>`: looser than `+` and `-`, tighter than `==`, `!=`, `AND`, and `OR`. `1 + 1 IN {a}` is `(1 + 1) IN {a}`, and `{v} IN {a} == TRUE` is `({v} IN {a}) == TRUE`.

#### Text is never an array

A text value stays text, even when it looks like a JSON array. `"[1,2]".LENGTH` is 5, `.CONTAINS` and `IN` look for a substring, `.SLICE` cuts the text, and `FOR` walks its characters. An array comes from an `ARRAY` variable, an array literal, `.SPLIT`, `.JSON.KEYS`, an array method, an `AS ARRAY` cast, or a member used directly as the collection.

A message on `sensors/batch`:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
{
  "values": [10, 20, 30]
}
```

`SumReadings` keeps that array, publishes a count of `3` and a sum of `60.0`, then publishes each element:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION SumReadings
ON TOPIC "sensors/batch" DO
    SET readings AS ARRAY = PAYLOAD.values
    PUBLISH TOPIC "sensors/batch/count" WITH PAYLOAD.values.LENGTH
    PUBLISH TOPIC "sensors/batch/sum" WITH {readings}.SUM
    FOR v IN PAYLOAD.values
        PUBLISH TOPIC "sensors/batch/one" WITH {v}
```

`SET "v" WITH PAYLOAD.values` stores the JSON text, which is a string. Use `SET v AS ARRAY = …` to keep an array. An array-only method such as `.FIRST`, `[0]`, or `.SUM` on text parses JSON-array text, because those have no text meaning. Other text raises, for example `FIRST requires an array receiver.` `AS ARRAY` on text that is not a JSON array raises `Cannot convert 'abc' to ARRAY`.

`PAYLOAD.FIRST`, `PAYLOAD.SUM`, and the other array-only methods on `PAYLOAD` parse JSON-array text the same way. After `{arr}.SLICE(start, end)` on an `ARRAY`, those methods chain (`{arr}.SLICE(0, 2).SUM`). `.SLICE` on text returns text. An array method after that `.SLICE` is refused when you deploy, with a message that `.SLICE of text returns text`.

Walk the elements with `FOR`. The loop variable holds each element, not its index. See [Loops](https://docs.coreflux.org/latest/lot-language/actions/operations.md#loops).

## Member access

`GET JSON` is soft-deprecated. It still works, but write new actions with member access: `PAYLOAD.temperature`, `report.unit`. A member reads, writes, deletes, and lists keys on the same value. A missing key and a JSON `null` read as NULL. `AS STRING` of NULL is `""`.

| Form | Meaning |
| - | - |
| `PAYLOAD.temperature`, `PAYLOAD.devices[0].id` | Read a field, or an array element with `[n]` |
| `report.unit`, `{report}.unit`, `(expr).unit` | Read a field of a variable or an expression |
| `report.HAS("unit")` | True when the key is present. Takes a string literal |
| `SET report.unit = "C"` | Write a field (`TO` and `WITH` work in place of `=`) |
| `DELETE report.unit` | Remove a field |
| `report.KEYS`, `report.KEYS.LENGTH` | The object's own keys as an `ARRAY OF STRING`, and how many there are |
| `report.LENGTH` | The keys of an object, the entries of an array, or the characters of text |

`GET JSON "devices.0.id"` becomes `PAYLOAD.devices[0].id`. An index past the end reads NULL.

**Where the short form applies.** The value before the first `.` must be `PAYLOAD`, a braced `{x}`, a parenthesised expression, or a name the action has already bound: a `SET` target, an `INPUT`, a `RETURN` name from `CALL ACTION`, `CALL PYTHON`, `CALL MCP`, `CALL LLM` or `CALL AGENT`, or a `FOR` variable. A dotted name that starts with anything else keeps its 2.22 meaning, such as a model field path `performance_metrics.target_cycle_time`.

**Methods and members.** After `.`, an uppercase LoT method name or keyword is a method: `UPPER`, `ROUND`, `KEYS`, `HAS`, `LENGTH`, `DELETE`, `JSON`, `TO`, a connector status field, and the other method names on this page. Anything else is a member, including lowercase names and uppercase names that are not methods, such as `ID` or `PV`. So `PAYLOAD.name.UPPER` applies `UPPER` to the member, and `{x}.trim` reads the key `trim`.

**Keys spelled like a method.** Quote the key, or use the explicit `.JSON.` form. Quote a key that has characters a name cannot have, too. A message on `plant/limits` can look like this:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
{
  "MAX": 90,
  "temp-1": 72.4
}
```

`ReadOddKeys` reads both keys. The quoted form and `.JSON.` both return `90`, and `"temp-1"` returns `72.4`:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION ReadOddKeys
ON TOPIC "plant/limits" DO
    SET "max" WITH PAYLOAD."MAX" AS INT
    SET "also_max" WITH PAYLOAD.JSON.MAX AS INT
    SET "temp" WITH PAYLOAD."temp-1" AS DOUBLE
    PUBLISH TOPIC "plant/limits/max" WITH {max}
```

`.JSON.` is the explicit form, and every short form above has one: `PAYLOAD.JSON.temperature`, `SET report.JSON.unit = "C"`, `report.JSON.unit.DELETE`, `PAYLOAD.JSON.KEYS`. Inside `.JSON.`, every bare segment after a dot is read as a key name, so keep `.JSON.` (or a quoted key) for keys spelled like a method, and prefer the short form everywhere else.

A message on `plant/report`:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
{
  "device": { "location": "line-A" },
  "devices": [
    { "id": "press-01" },
    { "id": "oven-02" }
  ],
  "alarm": "overtemp"
}
```

`ReadPlant` reads the nested location, the first device id, and the alarm. `{line}` is `line-A`, `{first_id}` is `press-01`, and `has_alarm` is true:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION ReadPlant
ON TOPIC "plant/report" DO
    SET "line" WITH PAYLOAD.device.location
    SET "first_id" WITH PAYLOAD.devices[0].id
    SET "has_alarm" WITH PAYLOAD.HAS("alarm")
    PUBLISH TOPIC "plant/line" WITH {line} + " " + {first_id}
    IF {has_alarm} THEN
        PUBLISH TOPIC "plant/alarm" WITH PAYLOAD.alarm
```

To build or change JSON, declare an object with `SET name AS OBJECT`, then write keys with `SET name.key = value`. A write creates missing objects along the path. `DELETE` removes a key, and deleting a key that is not there, or under a key that is not there, does nothing. `PAYLOAD` and `RESULT` are read-only. An object literal `{…}` is accepted only as the starting value of `SET name AS OBJECT = {…}`, not elsewhere in an expression or a `PUBLISH`.

A message on `sensors/temp` is a single number:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
21.5
```

`BuildReport` copies that number into `value`, adds the location, and drops `draft`:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION BuildReport
ON TOPIC "sensors/temp" DO
    SET report AS OBJECT = {"sensor_id": "TEMP01", "draft": 1}
    SET report.device.location = "line-A"
    SET report.value = PAYLOAD AS DOUBLE
    DELETE report.draft
    PUBLISH TOPIC "reports/temp" WITH {report}
```

That publishes an object with `sensor_id` `TEMP01`, `device.location` `line-A`, and `value` `21.5`. The `draft` key is gone. An object or array is published as indented JSON over several lines, so compare it as JSON, not as a fixed string.

A failed write raises a runtime error you can catch with `TRY` or `ON ERROR`, and the variable keeps the value it already had. Writing through a key that holds a value which is not an object, or into a string that is not JSON, fails this way. An index at the end of the path replaces that element. An index outside the array raises `JsonSetMember: array index N out of range.` `DELETE` on a final index removes that element and closes the gap. `DELETE` on an index outside the array raises `JsonDeleteMember: array index 5 out of range.`, and the array keeps its value. `DELETE` through a key that holds a value which is not an object or array raises `JsonDeleteMember: intermediate exists but is not a JSON object.` (or `… JSON array.`). On a string that is not JSON it raises the same message as a write. A missing key, or a missing key on the way to it, is not an error: there is nothing to delete, and the value is unchanged. An index in the middle of the path may create a one-element placeholder when the index equals the current length.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION ReplaceFirst
ON TOPIC "demo/list" DO
    SET report AS OBJECT = {"devices": [10, 20, 30]}
    SET report.devices[1] = 99
    DELETE report.devices[0]
    PUBLISH TOPIC "demo/list/out" WITH {report}
```

This publishes an object whose `devices` array is `[99, 30]`.

A message on `demo/plant`:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
{
  "press": { "state": "run" },
  "oven": { "state": "idle" }
}
```

`ListDevices` publishes `2` on `demo/device_count`, then each key name on `demo/device_key`:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION ListDevices
ON TOPIC "demo/plant" DO
    SET "keys" WITH PAYLOAD.KEYS
    SET "count" WITH PAYLOAD.KEYS.LENGTH
    PUBLISH TOPIC "demo/device_count" WITH {count}
    FOR name IN {keys}
        PUBLISH TOPIC "demo/device_key" WITH {name}
```

See [Working with JSON](https://docs.coreflux.org/latest/lot-language/usage-patterns/working-with-json.md) for payload shapes and `PUBLISH MODEL`.

## Connector status

Read a connector's live status from its name. Use the name you gave `DEFINE CONNECTOR`, then the field:

| Field | What it tells you |
| - | - |
| `CONNECTED` | Whether the connector is connected |
| `CONNECTION` | The connection state |
| `HEALTH` | The health indicator |
| `TYPE` | The connector type |
| `UPTIME` | How long it has been running |
| `CONNECTED_SINCE` | When the current connection started |
| `WARNING` | A warning from the connector |
| `TIMESTAMP` | When this status was read, as UTC text |
| `ERRORS_TOTAL` / `ERRORS_CONSECUTIVE` | How many errors in total, and in a row since the last success |
| `ERRORS_RATE` | The error rate |
| `MESSAGES_TOTAL` / `MESSAGES_SUCCEEDED` / `MESSAGES_FAILED` | How many messages it processed, and how many succeeded or failed |
| `LAST_ACTIVITY` / `LAST_SUCCESS_AT` / `LAST_ERROR_AT` | When it last did anything, last succeeded, or last failed, as UTC text |
| `LAST_ERROR` or `LAST_ERROR_MESSAGE` | The text of the last error |

Field names are uppercase only: `PlantDB.connected` is refused when you deploy. The fields are read-only.

An unknown name raises. A disabled connector raises `Connector 'X' is disabled`. On a cluster standby node, `plc.CONNECTED` and the other status fields raise instead of reading `TRUE` when another node owns the connector. The same fields are published as JSON on `$SYS/Coreflux/Routes/<connector_name>/status`. See [Connector status monitoring](https://docs.coreflux.org/latest/lot-language/routes/overview#connector-status-monitoring) and [Where LoT runs](https://docs.coreflux.org/latest/mqtt-broker/clustering.md#where-lot-runs).

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE ACTION WatchPlantDb
ON EVERY 30 SECONDS DO
    TRY
        IF PlantDB.CONNECTED EQUALS TRUE THEN
            PUBLISH TOPIC "status/db" WITH "up"
        ELSE
            PUBLISH TOPIC "status/db" WITH "down"
    CATCH
        PUBLISH TOPIC "status/db" WITH ERROR.MESSAGE
```

## Best practices

> [accordion] Check before you cast
>
> Read with no cast. `IF {raw} EQUALS EMPTY THEN` set a default, `ELSE SET "n" WITH {raw} AS INT`. Inside `TRY` or an action with `ON ERROR`, casting a missing topic, or the text `abc`, raises. Outside, it quietly gives `0`, which can hide a bad reading.

> [accordion] Reassign array methods
>
> `.APPEND`, `.REMOVE_AT`, and `.SORT` return a new array. `SET` the result if the next line should see it.

> [accordion] Keep times in UTC
>
> `TIMESTAMP.NOW.UTC`, `.ADD`, and `.FORMAT` are UTC. `ON CRON` is UTC by default. For a local wall-clock schedule, add `WITH TIMEZONE "<IANA name>"` to `ON CRON`. See [Local time zones](https://docs.coreflux.org/latest/lot-language/actions/events.md#local-time-zones).

## Next steps

> [card] [Operations](https://docs.coreflux.org/latest/lot-language/actions/operations.md)
>
> Loops, TRY, ON ERROR, and the topic reads these methods sit on.

> [card] [Action triggers](https://docs.coreflux.org/latest/lot-language/actions/events.md)
>
> Edges, timer-on, cron, and several ON clauses on one action.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.