Lua
A Lua transformer gives you a small script to work with your data: parse structures, apply logic, build new values, and pass extra data along the chain with ctx.
You'll find Lua in:
- Actions / Transformers pipe on an HTTP data source or HTTP destination — after (or between) HTTP requests in that list.
- Data source transformers — MQTT, WebSocket, and Timer: reshape incoming data before it's stored.
- Data piece transformers — reshape the root source value for this data piece.
- Component transformers — format or compute a value for display.
- Tap actions — more complex logic, building a message to send, and multi-action workflows. Add them on the data piece or on a component.
- Periodic action pipes — Lua on an interval to change how components look. Add it on the data piece, a group, a Freeform section, a custom screen, or a bottom sheet. See Periodic action pipes.
In any of those chains, tap a row to edit it, drag the handle to reorder, and swipe right to left to delete a transformer or action.
Your script's return value becomes the value the next transformer or action receives.
Quick reference
| Goal | Idea |
|---|---|
| Where it runs | Data transformers pipe on a data source, data piece, or component. Tap actions pipe when you tap a data piece or component. Periodic action pipes on a data piece, a group, a Freeform section, a custom screen, or a bottom sheet. |
| Read data / fields | Globals value, value.field, value["key"], value[1] (Lua tables count from 1) |
| Same data as expressions | Lua uses the same names (value, ctx, env, …), just as script globals instead of typed paths. |
| Connection error in transformers | ctx.error.message, ctx.error.kind, sometimes ctx.error.statusCode; set ctx.error = nil to mark it handled. |
| MQTT details | ctx.transport.topic, ctx.transport.receivedAt, … when ctx.transport is present. |
| HTTP | ctx.transport.responseTime, ctx.transport.statusCode, ctx.transport.url, ctx.transport.requestHeaders, ctx.transport.responseHeaders, … |
| WebSocket | ctx.transport.event, ctx.transport.mode, … |
| Timer tick | ctx.transport.reason, ctx.transport.intervalMs, ctx.transport.receivedAt. |
| Convert Lua tables ↔ JSON text | json_encode(x), json_decode(str). |
| Binary ↔ base64 text | base64_encode(x), base64_decode(str). |
| Read another data source | source_value("Name"), source_raw("Name"). |
| ENV variable | env.my_key. See ENV variables. |
| Format a timestamp | string.sub and tonumber. Do not use Lua %d in string.match. Text length: string.len, not #. os.time needs integers. |
| Return a result | return the new value for the next transformer or action. |
See also JSONPath, Expressions, Expressions in editors, and Periodic action pipes.
Where it runs
Data transformers pipe runs on a data source (MQTT, WebSocket, Timer), a data piece, or a component. HTTP sources and destinations use the Actions / Transformers pipe instead — Lua there sees the same names as a source transformer (value, raw, ctx, env). Tap actions pipe runs on a data piece or component when you tap it. If the data piece has tap actions turned on, the tap does not reach components.
Which globals your script can see depends on where it runs.
Globals: transformer vs tap action
Data transformer (source, data piece, or component)
value— live: the current data moving through this transformer chain, replaced by each transformer's result before the next one runs.raw— fixed for this chain: a snapshot ofvaluefrom the start of the chain, before any transformer in it changed anything. This is not the same as the tap "state after source transformers" snapshot below.ctx— details for this run.ctx.erroris a connection error, ornil. Details about the message itself may appear underctx.transport. Changes are visible to later transformers in the same chain.transformed— not available in data transformers (tap actions only).env— app-wide text from ENV variables. Readenv.my_key. If the key is missing, Lua seesnil(a simple expression seesnull). Same in transformers and tap actions.vars— app-wide values that scripts keep while the app runs. Read and writevars.my_key; set it tonilto remove it. Not saved. See Runtimevars.params— on a custom screen only: values passed when the screen opened (params.room).comp/components— on a data piece or component only: change how components look for this run (not saved). See Change how a component looks.
Tap action
value— live across the tap's actions.raw— fixed for the whole tap: the source's data right after its own transformers ran.transformed— fixed for the whole tap: whatever the data piece was showing when you tapped it. May be nil if nothing was set. Not available in data transformers.ctx— a shared Lua table for passing data between actions and holding connection details; always a Lua table during a tap (it may start out empty).env— same app-wide text as in transformers.comp/components— same as in a data piece or component transformer.
Summary (live vs fixed):
| Name | In a data transformer | In a tap action |
|---|---|---|
value |
Live, changes after each transformer | Live, changes after each action |
raw |
Fixed: value at the start of the chain (or the Actions / Transformers pipe) |
Fixed: data right after the source's transformers (or the Actions / Transformers pipe) |
transformed |
Not available | Fixed: what the data piece showed when you tapped it |
ctx |
Live, including the connection error state | Always a Lua table |
env |
App-wide text (env.my_key) |
Same |
comp |
This component (runtime look only). On a data piece script: comp.bgColorId. |
Same |
components |
Other components on this data piece, by ID (runtime look only) | Same |
What a script returns
- The editor stores a small script: some statements, ending with a
return. - The first value returned is what the transformer or action passes on (usually becomes the next transformer or action's
value). - An empty script does nothing.
- A typo or syntax mistake is caught before the script runs; a mistake while running shows up as an error with a message.
Example (transformer — extract and convert a temperature):
if type(value) == "table" and value.temp ~= nil then
return value.temp * 1.8 + 32
end
return value
Example (tap action — remember the tap time):
ctx.lastTap = os.date("!%Y-%m-%dT%H:%M:%SZ")
return value
Passing extra data with ctx
value is the main data. Later transformers or actions often replace it. Put anything you still need on ctx.
In a transformer chain, later transformers in that same chain see the write:
ctx.unit = value.unit
return value.temperature
The next Lua, expression (ctx.unit), or JSONPath ($.ctx.unit) can read it. Extra keys you set on a source transformer do not copy to component transformers — components get a copy of ctx.error and ctx.transport (when the source provided it).
In a tap chain, the same bag is shared across actions:
ctx.note = value
return { command = "set" }
Later: ctx.note in Lua or an expression, {{ ctx.note }} in HTTP request, MQTT send, WebSocket send, or destination fields, or $.ctx.note in JSONPath.
An HTTP request with Apply result → ctx key stores the response body under that key and leaves value unchanged.
Don't overwrite error or transport. Put your own extras on other ctx keys (for example ctx.unit); do not mix them into ctx.transport. ctx is always a Lua table — write if ctx.error then, never if ctx and ctx.error.
Set ctx.stopPipeline = true to skip every remaining transformer or action in this run. The current script still finishes and its return value is kept. Stop pipeline does the same without a script.
See Tap actions and Data transformers.
Change how a component looks
On a data piece or component transformer or tap action (not on a data source or HTTP list), Lua can change how components look until the next run. The change is not saved.
comp.visible = false
comp.textColorId = "error"
components.label1.value = "Overheating"
return value
compis the component this script is on. On a data piece script,comp.bgColorIdsets the data piece background. These writes set the look to aim for.componentsis other components on the same data piece, by ID.comp.userDatais the Data setting of this component, andcomponents.label1.userDatathat of another component on the same data piece. Both are read only. Text that is a JSON object or array becomes a Lua table,true/falsea boolean, a plain number a number, anything else stays text.- On a Freeform section, a component on the canvas (not inside a group) can move while that section is on screen. Set Anchor X, Anchor Y, and Rotation in canvas units. Width and height stay as they are. On tap, On change, On delete, On link tap, On row tap, and On point tap are not script properties.
returnstill movesvalue. In a transformer on that component, do not setcomp.value— return the new value instead.components.label1.valuecan change what another component shows.- Set a property to
nilto drop that runtime change. - A simple expression or JSONPath on the same data piece can read these names (
comp.visible,components.label1.value,$.comp.visible). They cannot write them — use Lua or JavaScript. - Inspector fields with
{{ }}do not have these names. - For app-wide state, use
vars(see Runtimevars).
If you rename a component's ID, scripts and expressions that mention that ID are updated. A Lua local variable with the same name is also rewritten.
Lua tables and structured data
- By default, objects and lists coming from the source arrive as Lua tables you can index and loop over.
- If that option is turned off in the transformer, structured data may arrive as JSON text instead — use
json_decodeto turn it into a Lua table. - File and image values arrive as binary, not a Lua string.
#valueis the byte length.type(value)isuserdata.#does not work on a Lua string — usestring.len. You can put the value in a Lua table (return { binary = value }) and send only{{ value.binary }}.
Lists built from incoming data are 1-based in Lua — the first item is t[1], not t[0].
JSON and Base64 helpers
These functions are always available:
json_encode(value)— turns nil, booleans, numbers, strings, and nested Lua tables (with no cycles) into a JSON string. On failure it returnsnilplus an error message. Binary values cannot be encoded — usebase64_encodefirst.json_decode(str)— parses JSON text into nil, booleans, numbers, strings, arrays (Lua tables with sequential number keys), or objects (Lua tables with text keys). It's forgiving about minor issues like typographic quotes in hand-typed JSON. On failure it returnsnilplus an error message.base64_encode(x)— turns binary data (or a Lua string) into base64 text. On failure it returnsnilplus an error message.base64_decode(str)— turns base64 text into binary data. Spaces and line breaks in the text are ignored. On failure it returnsnilplus an error message.
Use the JSON helpers to turn structured data into text and back. Use the Base64 helpers to turn binary into text and back.
Other data sources
You can read any other data source by its display name (not case-sensitive):
source_value("Name")— that source's currentvalue, after its own transformers ran.source_raw("Name")— the last message that source received, before its transformers ran (nilif nothing has arrived yet).
An unknown or empty name returns nil plus an error message, the same way json_decode does on failure.
While a transformer on source X is running, value and raw describe that chain; source_value("X") still returns the previous stored value until the chain finishes.
Lua vs JavaScript vs JSONPath vs expressions
- Lua reads
value,raw,ctx,transformed,env,varsas script globals, when they're available, pluscomp/componentson a data piece or component. In data transformers,rawis the snapshot from the start of the chain, andtransformedisn't provided. - JavaScript reads the same names. Its lists start at 0, and helpers are spelled
sourceValue,JSON.parse,base64Encode. - JSONPath starts every path at
$. In transformers,$.value…reads the data,$.raw…the start of the chain,$.ctx…extras,$.env…and$.vars…variables. On a data piece or component it can also read$.comp…and$.components.<id>…. - Expressions use plain names like
value,ctx.transport.topic, andenv.my_key, plussource_value("Name")/source_raw("Name")for other sources. In data transformers, expressions havevalue,raw,ctx,env, andvars— notransformed. On a data piece or component they can also readcomp/components.
All four work with the same ideas, just with different syntax and slightly different names available depending on where they run. A comparison table is in Expressions in editors.
Handling connection errors
When a connection fails, a source's Lua transformer receives ctx.error as a Lua table with message, kind, and statusCode (when one is available).
After success, or once the error has been handled, ctx.error is nil.
A source's Lua transformer can mark the error as handled:
ctx.error = nil
return value
Later transformers in the chain see the cleared state, and so does every component using that source. If the source leaves the error in place, each component gets its own copy of the details — clearing ctx.error in a component Lua transformer only affects that component.
To turn a connection error into a hard stop for the chain, raise it explicitly:
error(ctx.error.message)
This is different from ctx.error itself — raising an error stops the rest of the current chain. After a component's transformers run, a remaining ctx.error is available to later transformers in that component chain. When a transformer throws, the component shows a red #error above it in the editor. Connection health stays on the status dot and in the connection log.
MQTT: ctx.transport
For an MQTT data source, when ctx.transport is present, it describes the most recently received message (the decoded body is still value). ctx.transport is a Lua table with text keys, for example:
topic— the MQTT topicpayload— the same decoded body asvaluefor that messageqos,retain,protocolVersion,receivedAt(ISO 8601 text, UTC)- On MQTT 5:
retainAsPublished,contentType,userProperties,responseTopic,correlationData(base64 text),messageExpiryInterval, and similar fields when the broker sends them.
Tap actions that carry connection details in ctx use the same shape.
HTTP: ctx.transport
For an HTTP data source or destination, and for a tap HTTP request, ctx.transport describes the last HTTP request in that list (success, HTTP error, or timeout). Every HTTP request overwrites it. The body stays in value (or the ctx key you chose), not in transport.
method— GET, POST, …url— the address that was requestedrequestHeaders— a Lua table of request header names to values (names are lowercase; several values for one name are joined with a comma)statusCode— when a response arrivedresponseTime— how long the request took, in millisecondscontentType,charset— when the response sent themresponseHeaders— a Lua table of response header names to values (names are lowercase; several values for one name are joined with a comma). Example:ctx.transport.responseHeaders["content-type"]receivedAt— ISO 8601 text, UTC
Stop pipeline if failed is on unless you turn it off. A server error, a timeout, or a lost connection then stops the rest of the list. The request still replaces ctx.transport, and ctx.error is set. Turn it off for site monitoring so a later script can still run.
A Lua / JavaScript / Simple expression / JSONPath error always stops the rest of that list. For site monitoring, turn the switch off, then clear ctx.error with ctx.error = nil.
Use responseTime to show how long the request took — for example:
return ctx.transport.responseTime or 0
WebSocket: ctx.transport
For a WebSocket data source, when ctx.transport is present, it describes the most recently received message (the body is still value):
mode—websocket,sse, orsocket.ioevent— Socket.IO or SSE event name; raw WebSocket usesmessagepayload— the same decoded body asvalueurl— the shared connection addressreceivedAt— ISO 8601 text, UTC- On SSE,
idwhen the server sent a last-event id
Tap actions that carry connection details in ctx use the same shape.
Timer: ctx.transport
For a Timer data source, ctx.transport describes the last tick:
reason—interval(timer),trigger(manual / Trigger data source(s)),defaultValue(Default value on load or edit), orpeer(another source's value changed)intervalMs— the timer intervalreceivedAt— ISO 8601 text, UTC
Strings, patterns, and time
string.match, string.find, string.gsub, and string.gmatch use regular expressions, not Lua patterns.
%d,%a, and%sdo not mean digit, letter, or space. They match those characters as written. A timestamp like2026-08-25T08:48:11Zwill not match"(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d)". The usual result isnil, not an error — so a fallback such asreturn "Updated: " .. tsstill shows the original ISO text.- Use
\d(digit),\w(letter or digit),\s(space). In a Lua string in quotes, write a backslash as\\:"\\d{4}"is the pattern\d{4}(four digits). string.matchreturns only the whole match, not the pieces in parentheses.local y, m, d = ts:match("...")puts the full match inyand leavesmanddasnil.string.gsubreplacement is a string only (not a function). Use$1for the first group, not Lua's%1.#son a string fails withattempt to get length of a string value. Usestring.len(s).#still works on a Lua table (a list or map) and on binary incoming data.- Remainder is
%:hour % 12. Instring.formatandos.date, write one%per piece ("%02d","!%w").%%in a format string prints a percent sign. Do not write%%for remainder —hour %% 12is a syntax error near%. - For a fixed-format timestamp, prefer
string.subandtonumber:
local ts = value.updated_at
if type(ts) ~= "string" then
return "Updated: N/A"
end
local y = tonumber(string.sub(ts, 1, 4))
local month = tonumber(string.sub(ts, 6, 7))
local day = tonumber(string.sub(ts, 9, 10))
local hour = tonumber(string.sub(ts, 12, 13))
local minute = tonumber(string.sub(ts, 15, 16))
if not y or not month or not day or not hour or not minute then
return "Updated: " .. ts
end
local months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
return "Updated " .. months[month] .. " " .. day .. ", " .. y
.. " at " .. hour .. ":" .. string.sub(ts, 15, 16) .. " UTC"
os.time and os.date:
os.time({ year = y, month = m, day = d, hour = h, min = min, sec = 0 })needs integers. Text such as"2026"fails withfield 'year' is not an integer. Calltonumberfirst.- Those date numbers are the device's local clock, not UTC. Do not pass a server UTC timestamp's clock numbers into
os.timeand then format withos.date("!...")— the hour (and sometimes the day) will shift. os.date(format)formats the current time.os.date(format, t)formats the Unix timet. Start the format with!for UTC.- Useful pieces:
%Yyear,%ytwo-digit year,%mmonth,%dday,%H24-hour,%I12-hour,%Mminute,%Ssecond,%pAM/PM. - Names:
%Aweekday (Monday),%ashort weekday (Mon),%Bmonth (January),%bshort month (Jan). Names are always in English. - Numbers:
%jday of the year (001–366),%wweekday number (0is Sunday),%zoffset from UTC (+0300). - Ready-made:
%cdate and time (2026-09-29 14:05:00),%xdate (2026-09-29),%Xtime (14:05:00). os.date("*t")returns a Lua table withyear,month,day,hour,min,sec,wday(1is Sunday), andyday.
Current time in UTC:
return os.date("!%Y-%m-%dT%H:%M:%SZ")
Sandboxing
To keep behavior predictable, Lua here can't load external files, use require, make HTTP, MQTT, or WebSocket sends, or call several os functions that touch the shell, filesystem, or process.
os.date still works for formatting times; put ! at the start of the format to get UTC. os.time date tables need integers — see Strings, patterns, and time. To send from a tap, use HTTP request, MQTT send, WebSocket send, or Trigger data destination — see Tap actions.
A script that runs longer than 2 seconds is stopped. The dashboard freezes for those 2 seconds, then the script errors. It does not run in the background.
Invalid scripts and errors
Common causes of a script failing:
- A syntax mistake in the script
- A runtime error from the script or a helper (
error(...),json_encodeon a Lua table with a cycle, a bad index,os.timewith text instead of integers, …) - Assuming the wrong shape for
value - Using a Lua pattern such as
%dinstring.match— it will not match digits, and anilmatch often falls back to the original text #on a string (#ts,#minStr) — usestring.len%%used as remainder (hour %% 12) — a syntax error near%
A syntax or runtime error stops the current chain right away. A nil match does not — the script keeps going, which is why a fallback can still show the original timestamp. Check what value actually looks like at that point in the chain, keep your return paths simple, and check ctx.transport before reading its fields — it is omitted when the source has no connection details for this run.
What's built in
What's available before your script even runs, aside from the chain names like value.
Base globals
print, assert, error, select, ipairs, pairs, next, load, pcall, xpcall, getmetatable, setmetatable, rawequal, rawlen, rawget, rawset, type, tostring, tonumber, _G, _VERSION
Lua library tables
package, string, table, math, coroutine
os (only these work)
os.clock, os.difftime, os.time, os.date
App helpers
json_encode, json_decode, base64_encode, base64_decode, source_value, source_raw