![]() |
uvi-script
Musical event scripting with Lua
|
Modern coding assistants — Claude Code, Cursor, Codex, and others — can be extremely effective at writing uvi-script, but they need a small amount of project-specific orientation to avoid common mistakes:
os.execute, io.open, io.read, …) or breaking the audio thread with busy-wait loops.The convention these tools follow is to look for an AGENTS.md file at the root of the workspace and treat its contents as standing instructions for the assistant.
.lua scripts live). The filename depends on the assistant you use:CLAUDE.md (most reliable; loaded automatically).AGENTS.md.The assistant will pick up the file automatically and use it as context for every prompt in that workspace. The content itself is tool-agnostic — only the filename differs.
Copy everything between the lines below into your CLAUDE.md or AGENTS.md (depending on the assistant — see the previous section):
# uvi-script — assistant guide
This workspace contains uvi-script Lua scripts. Each `.lua` file is a
standalone real-time event processor loaded by a UVI instrument. There is no
build step, no package manager, no module bundler — scripts are loaded as-is.
Full reference documentation:
https://lua.uvi.net
When you are unsure about a function signature or a parameter name, prefer
fetching the relevant page from the documentation above over guessing.
**Before writing any non-trivial script** — anything that resembles a
sequencer, arpeggiator, harmonizer, strummer, ensemble, generative
pattern, or voice-manipulation effect — start by browsing the working
example scripts at https://lua.uvi.net/_examples_page.html. The
canonical patterns for handling held-note sets, shared coroutines, voice
tracking, and multi-voice timing live there. Reusing one of those
skeletons is almost always better than reinventing the structure from
this guide alone.
---
## 1. Real-time safety (read this first)
Callbacks (`onNote`, `onRelease`, `onController`, …) execute on the audio
thread. Anything that blocks, allocates wildly, or syscalls there will glitch
the audio.
The sandbox does not expose blocking I/O or system access at all: the
entire `os` and `io` libraries are unavailable (no `os.execute`, no
`os.clock`, no `os.time`, no `io.open`, …), and `require` reaches only the
engine's own modules and `.lua` files beside the script or the preset. Do not
try to call the rest — they are not "discouraged", they are absent. For file
I/O or dialogs, use the **Async** APIs instead:
`browseForFile`, `loadSample`, `loadMidi`, `saveData`, `loadData`. They run
on a background thread and call back into the script thread when done.
Inside a callback or any `spawn`-ed coroutine, also avoid:
- Busy-wait of any kind. The Lua-classic `while os.clock() < t do end`
pattern would not even run here (`os` is unavailable), and any equivalent
loop on `getTime()` would still freeze the thread. Use `wait(ms)` or
`waitBeat(beats)` instead.
- Allocating large tables in a hot loop. Pre-allocate at script load time.
- Spamming `print` from a hot path — it is for debugging only.
## 2. Lua dialect
uvi-script runs **Lua 5.1**. This means:
- No LuaJIT, no FFI.
- No `goto` / labels (Lua 5.2+).
- No native bitwise operators (`&`, `|`, `~`, `<<`, `>>`). Use the provided
`bit` helpers if you need bit math.
- No integer division `//` (Lua 5.3+). It is a syntax error, so it takes the
whole script down at load with nothing but an aborted interface to show for
it — `math.floor(a / b)` is the 5.1 spelling.
- Available standard libraries: `math`, `string`, `table`, plus a `bit`
library for bitwise ops. The `os` and `io` libraries are **not** exposed
at all — no `os.clock`, `os.time`, `os.date`, no `io.*`. For wall-clock
or musical time, use the engine APIs `getTime()` (ms since script load)
and `getBeatTime()` (current beat position).
- The `coroutine` and `debug` globals are hidden too (`require` still reaches
them; don't use it, it breaks the scheduler). Cooperative threading
is reached through `spawn` / `wait` / `waitBeat` (see below), never through
`coroutine.create` / `coroutine.yield`.
- The garbage collector runs on the audio thread budget. Do not call
`collectgarbage` aggressively.
- The compiler is stock Lua 5.1.4, so its fixed limits apply: **200 active
locals per function** — the main chunk is one, so every top-level `local`
counts, each name of `local a, b, c` separately, and a `for` adds three hidden
ones — and **60 upvalues per function**, i.e. a callback may refer to at most
60 distinct top-level locals. The errors read `main function has more than 200
local variables` and `function at line N has more than 60 upvalues`. Globals
do not count. Group constants and widgets into tables (one local, one upvalue)
and wrap one-shot setup in `do … end`; don't port a big KSP `on init` as one
`local` per variable.
- No single Lua allocation above about 1 MB succeeds (`not enough memory`): that
caps one string — including the JSON built from what `onSave` returns — and an
embedded script's source.
- An embedded script's errors are labelled `[string "<its first line>..."]:12:`
rather than a file name; the number is still the line.
## 3. Event-driven model
A script reacts to events by defining global callbacks. Names and casing
matter — the engine looks up these exact identifiers:
- `onInit()` — called once when the script loads.
- `onNote(e)` — incoming note-on.
- `onRelease(e)` — note-off.
- `onController(e)` — MIDI CC. Fields: `e.controller`, `e.value`.
- `onPitchBend(e)` — pitch bend.
- `onAfterTouch(e)` — channel aftertouch (note the camelCase).
- `onPolyAfterTouch(e)` — polyphonic aftertouch.
- `onProgramChange(e)` — MIDI program change.
- `onEvent(e)` — generic catch-all; use `e.type` against
`Event.NoteOn` / `Event.NoteOff` to discriminate.
- `onTransport(playing)` — host transport state changed (`playing` is a bool).
- `onSave()` — return a table of state to persist with the preset.
- `onLoad(state)` — restore state previously returned by `onSave`.
There is no `onIdle` callback — to run periodic work, use `spawn` with
`wait` / `waitBeat` (see threading section).
Note event fields (as carried by `onNote` / `onRelease`): `e.note`,
`e.velocity`, `e.layer`, `e.channel`, `e.input`, `e.vol`, `e.pan`, `e.tune`,
`e.slice`. When forwarding a note via `playNote`, real scripts often pass
the full set so the voice inherits the input's routing/expression.
Two further fields exist for `SampleMappingOscillator` only: `e.dim1` (logical
layer) and `e.dim2` (round-robin variant). They are absent on regular MIDI
notes; setting either before `postEvent(e)` routes the note to that zone set,
which is how a script switches articulation on a mapping oscillator — one
keygroup, one oscillator, one `<layer>` per articulation in the dmap:
```lua
function onNote(e)
e.dim1 = selectedArticulation -- 0-based, matches <layer> order in the dmap
postEvent(e)
end
```
`playNote` accepts them as well, as table fields or as its two last positional
parameters: `playNote{note=60, velocity=100, dim1=selectedArticulation}`.
**Forwarding rules.** If a callback is **defined** (even as an empty
function) the engine does NOT auto-forward — you decide whether to call
`postEvent(e)` or not. If a callback is **undefined**, the engine
auto-forwards the event via `postEvent(e)` for you.
This matters most for the NoteOn / NoteOff pair. If `onNote` swallows the
input (no `postEvent`), then `onRelease` must also be defined — at
minimum as an empty `function onRelease(e) end` — otherwise the engine
auto-forwards the matching NoteOff downstream and you get a spurious
release event for a voice your script never created.
To transform an event, modify `e` (or build a new event) and call
`postEvent(e)` from inside your defined callback.
## 4. Voices
A voice is one playing note. Voice manipulation functions take a `voiceId`,
which is returned when the voice is created:
```lua
function onNote(e)
local id = postEvent(e) -- forward the incoming note, capture its voice
local id2 = playNote(60, 100) -- C4 vel=100, sustain until released
local id3 = playNote(72, 100, 250) -- C5 vel=100, auto-release after 250 ms
end
```
`playNote(note, vel, duration?, layer?, channel?, input?, vol?, pan?, tune?,
slice?, oscIndex?)` — only `note` and `vel` are required. Production scripts
that forward an incoming note often pass the full set so the new voice
inherits the input event's routing and expression:
```lua
local id = playNote(e.note, e.velocity, -1, -- -1: released with the key
e.layer, e.channel, e.input,
e.vol, e.pan, e.tune, e.slice)
```
`duration` is the one to get right: `-1` (the default) releases the voice with
the key that played it, a positive value after that many ms, and `0` never —
only the note-on is sent, and the voice rings until you call `releaseVoice(id)`
yourself, typically from `onRelease`.
Once you have a `voiceId` you can use:
- `changeTune(id, semitones, relative?, immediate?)` — fractional semitones
(`0.01` = 1 cent, clamped to ±96); NOT cents.
- `changeVolume(id, gain, relative?, immediate?)` — **linear** gain, `1` =
unity, `0.5` ≈ -6 dB, `2` ≈ +6 dB (not clamped to 1) / `changeVolumedB(id, dB)`
- `changePan(id, pan, relative?, immediate?)` — pan in `[-1, 1]`
- `fadein(id, ms, reset?, layer?)`
- `fadeout(id, ms, killVoice?, reset?, layer?)`
- `releaseVoice(id)`
A `voiceId` becomes invalid after the voice ends (release or fadeout-with-kill).
Do not reuse it.
## 5. Cooperative threading
uvi-script uses cooperative coroutines, not OS threads. Two important
consequences:
- Each event callback (`onNote`, `onController`, …) already runs in its own
coroutine. That means you can call `wait(ms)` or `waitBeat(beats)`
**directly inside the callback** — you do not have to wrap it in `spawn`.
The canonical "do something while the note is held" pattern is a `while
isNoteHeld() do … wait(N) end` loop right inside `onNote` (see the
vibrato example below).
- Use `spawn(fn, ...)` only when you need work that **outlives** the
current event — e.g. a sequencer that keeps running across notes, or a
watchdog. `spawn` returns immediately; the spawned coroutine yields via
`wait` / `waitBeat` like any other.
`wait(ms)` and `waitBeat(beats)` are the only correct way to pause — never
busy-wait.
Useful query helpers from inside such loops: `isNoteHeld()` (true as long
as the note that triggered the current `onNote` is held), `isKeyDown(note)`
(true if a specific MIDI key is currently pressed).
## 6. UI widgets
Widgets are declared at the top level of the script (script-load time, not in
a callback). They appear as the script's user interface and **all of their
state is serialised automatically** with the preset — including the
contents of compound widgets like `Table` (every cell value is saved).
You do **not** need to copy widget values into `onSave` / `onLoad`; only
non-widget Lua state needs that (use `.persistent = false` to opt a
widget out of auto-persistence).
The convention in real scripts is to declare widgets as **globals**
(capitalised name) so they are reachable from any callback, then assign
`.changed` and call `:changed()` once to initialise display state:
```lua
Freq = Knob{"Freq", 4.0, 0, 10, unit = Unit.Hertz}
Freq.changed = function(self)
-- ... react to value change ...
end
Freq:changed() -- init once at load
```
Common patterns:
- The integer flag is the 5th positional argument: `Knob("Steps", 4, 1, 16, true)`.
- The widget's first argument is its **internal parameter name** — it must
be a valid identifier (letters, digits, underscore; **no spaces, no
parentheses, no punctuation**). For a human-readable label with spaces or
symbols, pass `displayName` as a keyword in the table-call form alongside
`tooltip`, `unit`, `bounds`, etc.:
```lua
PitchTable = Table{"PitchSt", MAX_STEPS, 0, -12, 12, true,
displayName = "Pitch (semitones)",
tooltip = "Per-step pitch offset"}
```
Using an invalid name like `Table{"Pitch (st)", ...}` errors at load with
`'Pitch (st)' is not a valid parameter name`. Most widget options
(`displayName`, `tooltip`, `unit`, `mapper`, `bounds`, `showLabel`,
`showValue`, `backgroundColourOff`/`On`, …) can be set the same way —
positional args first, keyword args after.
- Set `.tooltip` for hover help.
- Set `.persistent = false` on widgets whose state should not be saved
with the preset (e.g. transient indicators).
- For value formatting, **prefer `unit = Unit.X`** in the constructor
(table-call form) when the format is a standard one — the engine handles
the display, suffix, and locale. Available values: `Unit.Hertz`,
`Unit.Decibels`, `Unit.MilliSeconds`, `Unit.Seconds`, `Unit.Percent`,
`Unit.PercentNormalized`, `Unit.SemiTones`, `Unit.Cents`, `Unit.Pan`,
`Unit.LinearGain`, `Unit.MidiKey`, `Unit.Megabyte`, `Unit.Generic`. Fall
back to setting `self.displayText` inside `.changed` only when you need a
custom format the units don't cover. `displayText` only changes the on-screen
widget: host automation still shows the raw value, while `unit` also drives
the DAW's parameter text. `unit` is ignored on integer knobs (the 5th
positional flag), so use a float knob when you want a unit; for discrete
labelled steps, use a `Menu`.
- Mappers work the same way: `mapper = Mapper.Exponential` for log-style
knobs (e.g. frequency). **`Mapper.Exponential` requires a strictly
positive range** — `min` and `max` must both be > 0. A range like
`0.0 .. 5.0` errors at construction with `'Exponential Mapper range
should be strictly positive'`. When the range must include zero (e.g.
ADSR times that should be allowed to go to 0), use **`Mapper.Cubic`**
instead — it gives a similar curve-feel to Exponential but tolerates
zero. `Mapper.Linear` is the other fallback if you don't want any
curvature at all.
Widget types: `Knob`, `Slider`, `Button`, `OnOffButton`, `MultiStateButton`,
`Menu`, `NumBox`, `Label`, `Image`, `SVG`, `Panel`, `Viewport`, `Table`, `XY`,
`AudioMeter`, `WaveView`, `FileSelector`, `DnDArea`.
Parameter-bound widgets: `ParamKnob`, `ParamSlider`, `ParamOnOffButton`,
`ParamMenu`, `ParamNumBox` take an element and one of its parameter names
(`ParamKnob(osc, "FineTune")`) instead of a name/default/range, and
`ParameterValue` is the same binding with no control on screen. When the goal
is to put an engine parameter on the UI, these are the idiom, not a `Knob`
whose `changed` calls `setParameter` (see section 7).
## 7. Engine access — navigating the synthesis tree
A pure MIDI processor often does not touch the engine, but as soon as you
need to drive synthesis parameters, swap samples, or build a custom patch
UI, you traverse the synthesis tree. Get this part wrong and the LLM will
invent methods (`getLayer(0)`, `addModulator()`, …) that do not exist.
**Root globals** (always available, no construction needed):
- `Synth` — the master element (top of the tree).
- `Part` — the current part (in multi-timbral contexts).
- `Program` — the current program / patch. **The most useful entry point**
for almost every script.
- `Layer` — context shorthand.
`Program` and `Part.program` refer to the same thing in a single-part
patch.
**Hierarchy and indexing**:
```
Synth.parts[i] (1-indexed table of Part)
→ Part.program (single Program reference)
→ Program.layers[i] (1-indexed table of Layer)
→ Layer.keygroups[i] (1-indexed table of Keygroup)
→ Keygroup.oscillators[i] (1-indexed table of Oscillator)
```
All those collections index like Lua arrays: `[i]` works (Lua is
**1-based**), `ipairs(...)` iterates them, and `#` gives the count. They
are read-only views onto the engine, not plain Lua tables, so `table`
library functions (`table.insert`, `table.remove`, ...) do not work on
them.
**Effect chains and sends are 1-indexed arrays too.** On every level the
engine exposes:
- `.inserts[i]` — insert effects chain, in order. Index by integer.
- `.sends[i]` — send buses, in order. Index by integer.
- `.auxs[i]` — auxiliary effect buses (on `Synth`, `Part` and `Program`).
Index by integer.
In Falcon the Program and the Master (`Synth`) have 4 auxes or more: the
user can add and delete them. `.auxs` follows their position, and each Layer
and Keygroup (each Part, for the Master auxes) has one send per aux, in the
same order. Deleting an aux shifts the index of every aux after it, and of
the matching sends, by one. Saving and reloading keeps the positions.
```lua
local reverb = Program.inserts[3]
keygroup.sends[2]:setParameter("Gain", 0.5)
Program.auxs[1].inserts[4]:setParameter("Volume", 0.5) -- linear: ~-6 dB
```
`Gain` and `Volume` parameters are **linear** gains, not dB: `1` is unity and
`0.5` is about -6 dB. Writing `-6` there is not -6 dB — a negative gain inverts
the phase. Convert with `10^(dB/20)`.
**Modulations are the only string-keyed collection.** `.modulations` is a
dictionary keyed by the modulator's display name (the name visible in the
UI):
```lua
local ampEnv = Program.layers[1].keygroups[1].modulations["Amp. Env"]
local dahdsr = Program.modulations["DAHDSR 2"]
local multiEg = keygroup.modulations["Multi Envelope 1"]
```
`.modulations` is a plain table keyed by name, so `#` reads 0 on it and
`pairs` walks it in no defined order. To count or enumerate modulators, use
`.mods`: the same modulators as a 1-indexed array, in engine order, that
answers to `#` and `ipairs` like the collections above:
```lua
for i, mod in ipairs(kg.mods) do print(i, mod.name) end
```
**Parent references.** `keygroup.layer`, `layer.program`,
`oscillator.keygroup` walk back up the tree without recomputing the path.
**Uniform parameter API.** Every node inherits from `Element` and exposes:
```lua
node:setParameter(name, value)
node:getParameter(name)
node:hasParameter(name)
node:getParameterConnections(name) -- modulation/automation connections
```
Parameter names are strings (e.g. `"Pan"`, `"Gain"`, `"CoarseTune"`,
`"AttackTime"`, …). The canonical list per element type lives in the
**Elements** reference page of the documentation — when in doubt, fetch
it. Use `:hasParameter(name)` to guard the call:
- When you control both the script and the patch (you know the node
type and the parameter name exists by construction), prefer
`assert(node:hasParameter("X"))` at script-load time. Loud failure
beats silent skip — if a future patch tweak removes the parameter,
you find out immediately instead of silently no-op-ing.
- When the user can change the target node or the parameter name at
runtime (e.g. a "pick any insert / any param" mapper), use a silent
`if node:hasParameter(name) then node:setParameter(name, v) end` so
invalid combinations are forgiving rather than fatal.
**The tree is stable.** Layers, keygroups, modulators and oscillators are
configured in the patch — there is no public API to add or remove them
from a script (no `addLayer`, `addModulator`). A script *tweaks*
existing nodes; it does not build the patch. The one exception is insert
effect chains: `node:insertEffect(type, slot, cb)`, `node:removeEffect(slot, cb)`
and `node:moveEffect(from, to, cb)` on any node with `.inserts` (1-based slots,
nil slot = append). They are **asynchronous** — the chain changes after the
call returns, so re-read `node.inserts` in the callback, and check
`task.success` (false for an unknown type or a stale slot). `moveEffect` keeps
the effect instance (settings, modulation, audio tail, references); a removed
effect's reference expires. Cache references to the rest of the tree
once at script-load time:
```lua
local kg = Program.layers[1].keygroups[1]
local osc = kg.oscillators[1]
local ampEnv = kg.modulations["Amp. Env"]
-- Idiomatic: walk a layer's keygroups, set a parameter on each.
for _, keygroup in ipairs(Program.layers[1].keygroups) do
keygroup:setParameter("Pan", 0)
end
-- Put an oscillator parameter on the UI: a bound widget. It takes the
-- parameter's range, unit and curve, follows automation and preset loads,
-- and is saved with the patch — no `changed` handler to write.
Detune = ParamKnob(osc, "FineTune")
-- A plain Knob + `changed` only when the script must compute the value it
-- writes, e.g. one control driving several parameters.
Spread = Knob("Spread", 0, 0, 1)
Spread.changed = function(self)
for i, o in ipairs(kg.oscillators) do
o:setParameter("FineTune", (i - 1) * self.value)
end
end
Spread:changed()
```
**`loadSample`** targets a Sample Player oscillator, not a path or buffer:
```lua
loadSample(osc, "/path/to/sample.wav", function(task)
if not task.success then print("load failed") end
end)
```
**`loadMapping` is a method of the mapping oscillator, and a load reports
when it is done.** `osc:loadMapping(path, cb)` replaces the oscillator's zones
with the file's and `osc:clearMapping()` empties it. The callback fires once
the last zone has loaded — with `success = false` if a later `loadMapping` on
the same oscillator overtook this one, so a failed report is not always a bad
file. `osc:getLoadingStatus()` is the other way to know, for a loop that
waits: it reads 0 from the moment a load is requested rather than from when
the worker reaches it, so `while osc:getLoadingStatus() < 1 do wait(50) end`
does not fall through on its first pass. Neither wants a timeout beside it:
that is a guess at how long a disk takes, and a "loading" notice taken down
on a timer comes down while the samples are still arriving. Count the loads
you have outstanding and let the callbacks bring the count back to zero.
**The program owns its mapping; `loadMapping` is for switching at run time.**
A MultiSample oscillator's `MappingPath` is saved with the program and loaded
with it *before any script code runs* — zones and saved purge state are in
place, though the samples may still be arriving. Do not `loadMapping` the
program's own content in `onInit`: it would only exist after the first notes
were handled, which is silent live and a silent preview render. The pattern:
zones not needed at start-up marked `purged="1"` in the `.dmap`;
`osc:unpurgeZones(dim1, -1)` for the active articulation in `onInit`, with no
completion and no wait; at run time, unpurge the new layer with a completion,
set the `dim1` you route to inside it, and purge the old layer after. Never
wait for an `unpurgeZones` on `getLoadingStatus` (it can still read 1 until
the worker picks it up), never call `waitForLoading` (it blocks the audio
thread), and never use `wait()` as a loading delay: `wait` counts rendered
audio, so in a faster-than-realtime bounce `wait(30)` is almost no wall time.
Live, loading is asynchronous: even after the completion, the first streamed
blocks may still be arriving, so a note played right after an unpurge can be
dropped — that is load time, not a bug. Offline renders (DAW offline bounce,
preview, command line) block each note until its zones and sample data are in,
so notes render —
but completions land at a point in the audio that depends on machine speed, so
a script that drops notes until a callback fired renders differently each time.
Route to a layer that is loaded instead of dropping notes.
**Sample files carry the loops; the mapping carries everything else.** A
`.dmap` zone's root (`baseNote`, default 60), `tune`, `gain` and key/velocity
ranges come from the mapping only — the file's root and ranges are ignored —
while loop points, loop mode, crossfade and start/end are read from the file
(WAV `smpl`, AIFF `INST`/`MARK`, FLAC only via `flac --keep-foreign-metadata`).
The `.dmap` has no loop attributes; an `.sfz` region may override the file's
loop with `loop_mode` / `loop_start` / `loop_end` (inclusive) / `loop_crossfade`
(seconds), unset ones falling back to the file, then to the whole sample. Cue points,
regions, marker labels and FLAC Vorbis tags are never read. Porting a library:
roots and ranges into the `.dmap`, loops into the files' `smpl` chunks.
**Common LLM hallucinations to avoid**: `getLayer(i)` (use
`Program.layers[i]`), `addModulator(...)` (does not exist — set parameters
on existing modulators instead), `addEffect(...)` (it is
`node:insertEffect(type, slot, cb)`, asynchronous),
`Program:getLayers()` (it is a field `.layers`, not a method), 0-based
indices.
## 8. UI layout
The default Panel layout auto-flows child widgets — that works only if
the panel's size matches its content. Two rules to keep the UI from
looking broken:
1. **Build, then layout.** Declare all widgets and panels first. Set
geometry at the END of the script in a single block, with relative
positioning so panels flow consistently:
```lua
local margin = 10
oscPanel.x = margin
oscPanel.y = margin
oscPanel.width = 400
oscPanel.height = 60 -- one row of knobs
filterPanel.x = oscPanel.x
filterPanel.y = oscPanel.y + oscPanel.height + margin
filterPanel.width = 400
filterPanel.height = 60
setSize(650, 380) -- overall window
makePerformanceView() -- this script is the perf view (5.)
```
Use the `.x` / `.y` / `.width` / `.height` properties separately
instead of `panel.bounds = {x, y, w, h}` so later panels can refer to
`oscPanel.y + oscPanel.height` cleanly.
2. **Size panels to fit their content.** The engine uses a 120-px column
grid (one labelled widget per column). Practical rules:
- labelled Knob, Menu, or Slider: **~120 px wide × ~45 px tall**
(the engine default is `InnerColWidth × (2 * RowHeight + Margin)`
which is 110 × 45, with 5 px margins on each side → 120 footprint)
- Table: whatever you give it; typical 500 × 120
- Label / single-line widget: ~120 × 20
Panel width = `N * 120` for a row of N labelled widgets. Panel height
for a knob row is ~60 (knob + small header padding). For panels with
a Table + secondary row underneath, allow `tableH + 60`.
The factory monoBassLine uses **400 / 400 / 500 / 630** across its
four panels (3 knobs / 3 knobs / 4 knobs / Table+menu+knob); copy
that scale rather than guessing tighter.
3. **`setSize(W, H)` must match the bounding box of all panels.** Compute
from `math.max` of every panel's right edge plus a margin:
```lua
local totalW = math.max(oscPanel.x + oscPanel.width,
filtPanel.x + filtPanel.width,
envPanel.x + envPanel.width,
seqPanel.x + seqPanel.width) + margin
local totalH = seqPanel.y + seqPanel.height + margin
setSize(totalW, totalH)
```
4. **Inner widgets auto-flow.** Widgets created with `panel:Knob(...)`,
`panel:Menu(...)`, etc. position themselves left-to-right within the
panel as long as the panel is wide enough. Override with per-widget
`.x` / `.y` / `.width` / `.height` only for non-flow placement
(Tables, secondary indicators, etc.).
5. **`makePerformanceView()`** only sets a flag marking this script as the one
providing the program UI; the host reads the widgets later, from whatever
the script body built. It captures nothing, so it can go anywhere in the
script body. The one thing its position decides is what happens when the
load fails: the flag stays set past a later error, so called **early** the
performance view still shows the widgets declared before the failing line
(framed in red), while called last it is never reached and there is no
performance view at all. Always call it for instrument scripts.
## 9. Examples
### Good: vibrato (LFO loop running while the note is held)
This is the canonical idiom in production scripts: drive an LFO inside the
`onNote` callback, sample the value at a fixed period with `wait(ms)`, and
apply it to the voice via `changeTune`. `isNoteHeld()` returns true as long
as the originating note is held, which makes the loop self-terminating.
```lua
Freq = Knob("Freq", 4.0, 0, 10) -- Hz
Depth = Knob("Depth", 25, 0, 100) -- cents
function onNote(e)
local id = postEvent(e)
local phase = 0
while isNoteHeld() do
-- changeTune takes semitones: divide the cents knob by 100
changeTune(id, (Depth.value / 100) * math.sin(2 * math.pi * phase))
wait(5)
phase = phase + (5 / 1000.0) * Freq.value
end
end
```
### Good: velocity remap with a UI knob
```lua
Curve = Knob("Curve", 1.0, 0.25, 4.0)
function onNote(e)
e.velocity = math.floor(127 * math.pow(e.velocity / 127, Curve.value) + 0.5)
postEvent(e)
end
```
### Good: tracking voiceIds per held note
When several voices can play on the same note, track them in a table
indexed by note number so a later CC or release can address them:
```lua
heldVoices = {}
function onNote(e)
local id = postEvent(e)
heldVoices[e.note] = heldVoices[e.note] or {}
table.insert(heldVoices[e.note], id)
end
function onRelease(e)
postEvent(e) -- forward the note-off so the engine ends the voice
heldVoices[e.note] = nil -- ids are now invalid
end
```
### Good: persisting non-widget state with onSave / onLoad
Widgets serialise themselves (knob positions, table cells, menu selections,
…), so you only need `onSave` / `onLoad` for *Lua-side* state that has no
widget — or for widgets you deliberately opted out of auto-persistence
with `.persistent = false` and want to round-trip yourself. Real scripts
keep this minimal: return a table, restore from it, no defensive nil
handling:
The state goes through JSON, so a table that mixes array entries and string
keys comes back with its integer keys as *strings* (`t[1]` becomes `t["1"]`):
keep arrays and keyed records in separate tables.
```lua
recordedNotes = {}
function onSave()
return { recordedNotes = recordedNotes }
end
function onLoad(data)
recordedNotes = data.recordedNotes
end
```
### Bad: busy-wait — never do this
```lua
-- ❌ Won't even run: os is not exposed by the sandbox.
-- And even with a working clock, this would freeze the audio thread.
local t = os.clock() + 0.5
while os.clock() < t do end
```
```lua
-- ✅ Yield the coroutine. wait/waitBeat work directly inside callbacks.
wait(500)
```
### Bad: synchronous file I/O — not available in the sandbox
```lua
-- ❌ io.open / io.read / os.execute are not exposed; this will error.
local f = io.open("/path/to/file.wav", "rb")
```
```lua
-- ✅ Use the async API; the callback runs on the script thread.
-- loadSample requires a sample oscillator as its first argument — it loads
-- the file *into* that oscillator, it does not return audio data.
local osc = Program.layers[1].keygroups[1].oscillators[1]
browseForFile("open", "Select sample", "", "*.wav", function(task)
if task.success then
loadSample(osc, task.result, function(t)
if t.success then print("loaded", task.result) end
end)
end
end)
```
## 10. Failure modes, and where output goes
- **Errors are reported twice, with a line number.** Every uncaught Lua error is
printed to the script console in the host UI *and* appended to
`ScriptProcessor.log` — macOS `~/Library/Logs/<host>/ScriptProcessor.log`,
Windows `%APPDATA%\<host>\ScriptProcessor.log`. `print` output goes to the same
console. The log is the one that survives closing the editor, so it is the
better place to look after the fact.
- **An error while the script loads aborts everything after it.** Widget
declarations and `makePerformanceView()` past the failing line never run, so a
mistake in the middle of a script surfaces as an instrument with a missing or
empty interface. When that happens the cause is already written down — read the
console or the log rather than assuming the API is at fault.
- **Do not wrap everything in `pcall`.** A swallowed error is indistinguishable
from a value that is legitimately absent, which turns one bug into a wrong
conclusion about the API. Use `pcall` only where you are genuinely testing
whether something exists, and let everything else throw so it reaches the log.
The call most often wrapped is also one that never raises: `setParameter`
with a name the element does not have is not an error, it does nothing — so
`pcall(function() layer:setParameter("Mute", true) end)` reports success and
nothing is muted, because the parameter is `MidiMute`. The guard for a name
is `hasParameter`, and the place for it is script load.
- **`local` used before its declaration is the classic silent trap.** A `local`
is only visible to code compiled after it, so referring to one from a function
defined earlier resolves to a nil *global* — which fails when that function
runs, not where the mistake is:
```lua
local function caller() helper() end -- ❌ 'helper' is a nil global here
local function helper() end -- (declared too late)
```
Declare `local helper` up front, or order the definitions so callees come
first. The same applies to values: a `local` config table read from a function
written above it is nil at run time.
## 11. Traps worth knowing before you hit them
Each of these fails in a way that does not point at its cause.
- **Two widgets may not share a parameter name.** The second declaration aborts
the load, so the interface stops at that line — the symptom is a half-built
UI, and the cause is in the console with its line number. Names built from a
prefix are the easy way to collide by accident (`key .. "ArpRate"` written in
two places); if you generate names in a loop, it is worth grepping the script
for the suffixes you generate.
- **Never assign `.value` on another widget from inside a `changed` handler.**
Assigning it re-enters that widget's own handler; two widgets that set each
other — a radio group is the usual case — recurse until the C stack goes.
Use `widget:setValue(v, false)`, which moves the control and updates the UI
without calling back into the script. Pass `true` only when you *want* the
target's handler to run.
- **A note you post by hand is never released.** `postEvent{type =
Event.NoteOn, …}` creates a voice that no key owns: it plays to the end of its
sample, and the amplitude envelope's release never fires — so a release knob
appears to do nothing at all. `playNote` is what ties a voice to the key that
asked for it: its default `duration` of -1 registers the voice on the calling
note's thread and the engine releases it on note-off — by the key, not the
pitch, so a snapped or transposed note needs no record of what was really
played, where a transposed `postEvent(e)` needs its note-off transposed the
same way. That default means something only inside `onNote`. Anywhere else
the voice has no key to wait for, and the failures differ: from `onInit`,
`onTransport`, an async completion callback, or a coroutine spawned from the
script body or a widget's handler it is released on the spot, a click and a
tail; from `onRelease`, `onController` (any callback whose event is not a
note-on) or a coroutine spawned inside any callback, `onNote` included, it is
never released at all; and in a widget's `changed` handler run by a user
gesture it raises an error, because that handler runs outside any script
thread. A
sequencer's steps pass a positive duration, and 0 only when you will release
the id yourself — a gate that can reach 0 hands you the never-released case.
- **`XY` resolves its two names against the script's own parameters.** The pair
it drives has to be plain `Knob`/`Slider` widgets declared in the script. A
`ParamKnob` is a parameter of another element and does not exist under that
name, the lookup returns id 0, and the host goes down rather than reporting
it.
- **A connection is reachable from either end, but not the same way.** From the
source it is the `.connections` property, which exists on a
`ControlSignalSource` only — asking an insert for `.connections` raises. From
the destination you go through the **parameter**, not the element:
`node:getParameterConnections(name)`. That one returns a plain 1-based table
of every connection landing on that parameter, modulation connections first
and edition ones after.
```lua
-- Which connection drives this filter's cutoff, and where does it come from?
for _, c in ipairs(filter:getParameterConnections("Freq") or {}) do
print(c:getParameter("Source"), c:getParameter("Bypass"))
end
```
Note the `or {}`: with nothing connected the call returns **nil**, not an
empty table, so iterating it unguarded is the easy mistake.
- **A `Viewport` has no `backgroundColour`.** Colour the `Panel` you put inside
it; the viewport itself only takes the four `scrollBar*` colours and
`scrollBarThickness`.
- **Engine collections answer to `ipairs` and `#`.** They are read-only views,
so the `table` library does not work on them, but there is no need to guess a
bound or to probe indices until one fails.
- **A modulation source's `Depth` is not the amount your script controls.** A
`MultiLFO` with `Depth = 0` still swings: depth scales the shape, and what
decides how much of it reaches a destination is the **connection's `Ratio`**.
Set the amount there — `Depth = 0` on the source and a nonzero ratio still
modulates, which is the confusing half of it. A source shared by many
destinations is the case this matters for: one macro, one ratio per
connection, and each destination gets its own amount from one source.
- **Host automation slots run out.** Falcon has 128 for the whole plugin
instance, shared by every script in it. Past that, `widget.exported = true`
reports an error in the console and the parameter is not automatable; there is
no limit on widgets or parameters themselves.
- **`playNote`'s `oscIndex` is zero-based, and out of range it plays nothing.**
It also overrides the keygroup's own trigger rules, so it is the way to
address one oscillator of several in a keygroup. An index past the last
oscillator is not an error and does not fall back — the note is simply
silent.
- **A keygroup with no zone for the key still costs a voice.** The engine
allocates, the keygroup finds nothing, and the voice is handed back inside the
block — but it was counted first. So a program whose keygroups are a pool the
script loads mappings into spends its voice caps by the size of the pool: one
note against `NotePolyphony`, and a chord arriving in one buffer against the
layer's `Polyphony`. Both are on the Program. `NotePolyphony = 0` means
unlimited, which is usually what a pool wants; `Polyphony` is a stealing
threshold rather than an allocation, so raising it costs nothing while idle.
The symptom of getting this wrong is the *first* keys of a kit going silent
while the last ones sound, because stealing takes the oldest allocation.
- **`purgeZones` takes a round robin out of the cycle, not just out of memory.**
Zone picking skips zones that are not loaded, so purging variants 3..8 of an
articulation leaves the first two sharing the turns rather than leaving silent
hits every third note. That makes a reduced-round-robin version of an
instrument a call rather than a second set of mapping files. Purges are queued
on the oscillator's own worker queue behind the load that precedes them, so a
purge issued right after `loadMapping` prevents those samples being read at
all.
- **`MidiMute` on a layer drops its note-offs too.** It stops the layer's
dispatch whole, so a source switched off while a key is down keeps sounding
until the sample ends, and a release-triggered keygroup never hears the
note-off it is waiting for. Release the layer before muting it, and do it with
one event rather than a note-off per key you remember: `postEvent{type =
Event.ControlChange, controller = 123, value = 0, layer = n}` releases every
voice on that layer and no other — a posted event carries its `layer`, and a
layer accepts only its own. Controller 120 is not a substitute: All Sound Off
steals the voices instead, which cuts every tail mid-air.
- **A keygroup's key and velocity ranges are patch structure, not a gate to flip
per note.** Writing `LowVelocity`, `HighVelocity`, `LowKey` or `HighKey` takes
the keygroup out of the layer's keymap and puts it back, key by key, and a
script does that on the audio thread — once per write, per keygroup touched. A
source that should answer only part of the velocity range compares
`e.velocity` in `onNote` and does not play the note; the ranges stay what the
patch says and nothing is rebuilt.
- **`loadTextData` hands your callback the text, not a task.** Its sibling
`browseForFile` gives you a task whose `result` is the path, so the two read
alike and are easy to mix up: `loadTextData(task.result, function(text) … end)`
— indexing that string for a `.result` yields nil and the load silently does
nothing. And it is for text you mean to parse yourself: `saveData(table, path)`
writes a Lua table as JSON and `loadData(path, function(data) … end)` hands the
table back, so a bank of settings is saved and read as the table it already is,
with nothing to serialise by hand.
- **A relative path is tried from the script's folder, then from the preset's.**
Artwork, mapping files, samples and the files you save and load all resolve
the same way and in that order, so a bank keeps its assets beside its presets
and writes `../Artwork/knob.png` once. `require` walks the same two folders
for a `.lua` of that name: `require "arp"` finds `arp.lua` beside the script,
which is how a script is split into files and how two presets share one body —
a one-line preset script that sets a global and then requires the shared file.
- **A `Panel` with no background image paints one anyway.** It fills itself
with the look-and-feel's translucent black, so a panel used only to group or
to hide a row washes out everything under it — pass
`backgroundColour = "00000000"` for those. And a page whose background is
artwork should set the panel's own `backgroundImage` rather than add a child
`Image`: with a child image the panel still paints its fill underneath, and
two stacked pages then tint the art twice.
- **A `Label` centres its text vertically in its box**, so the box has to fit
the font. One height reused for several font sizes lifts the baseline of every
size it was not chosen for, which reads as labels that sit a few pixels too
high — the kind of thing you see only next to the original. Give each role its
own size and height. There is no letter-spacing property either: a tracked-out
caption is a string with the spaces typed in, so build those strings in one
function rather than by hand.
- **Anything you draw over a control takes its clicks.** Every widget intercepts
the mouse by default, a `Label` or an `Image` included, so a caption placed on
a knob, a readout over a bound box or a picture under a transparent menu leaves
the control dead in that rectangle — it looks skinned and does nothing. Set
`interceptsMouseClicks = false` on everything that is only there to be looked
at.
- **A bound widget's value is drawn by the widget, so style it there.** A
`ParamNumBox` takes `textColour`, `backgroundColour`, `font`, `fontSize` and
`align` like a `NumBox` does, and prints the parameter in the engine's own
words: for a synced rate, the note division rather than a frequency you would
have to spell yourself. Do not put a label of your own over one to recolour
it — you get two values on the one plate. `ParamKnob` is the exception: its
readout has no colour of its own, so a knob that has to read in your ink wants
`showValue = false` and a label you place yourself, fed by a `ParameterValue`.
- **A bound `Param*` widget is invisible to the script.** Its `changed` never
fires, its `value` is read-only and it has no `setValue`: the parameter is the
state and the widget is just a view of it. So anything that has to *move* one
— a randomise button, a "link these two controls" feature — writes the
parameter and lets the widget follow. If a control needs a script callback for
its own reasons, it cannot be bound — nor can a switch whose sense is the
opposite of its parameter's: a `ParamOnOffButton` on `Bypass` lights when the
section is off, and there is no property to invert it, so that one stays a
plain `OnOffButton` writing `not self.value`.
- **`ParameterValue` is the missing half of that.** It is a non-visual binding
to one parameter, and unlike the bound widgets its `changed` *does* fire —
whoever moved the parameter, be it a knob, automation or a preset load. With
`value` and `toString()` it is how you drive a label of your own while the
parameter stays the single source of truth, and `toString()` is the only way
to obtain the engine's own words for a value: there is no `getParameterText`,
and a parameter definition carries no formatter. It fires once as the
interface is built, with the string already filled, so there is nothing to
seed and no first frame to paint by hand. Create it in the script body like
any widget — one made later never gets a component, and its string stays
empty.
- **Restoring a preset calls your handlers, in declaration order.** Putting a
script parameter back invokes that widget's `changed`, so the restore writes
your values through your own code — which is usually what you want, and
occasionally a trap. A control that *loads samples or mappings* must not fire
while the preset is still arriving, or it will reload over what the preset
already carries: guard those with a flag you lift in `onInit`, and leave
everything else unguarded. A handler that touches *other* widgets runs against
whatever state they have at that point in the sequence: a menu that resets the
one under it belongs before it, and a control that couples knobs belongs after
them — or outside auto-persistence, carried by `onSave`, so it comes back last.
The order is: the program's mappings (structure only — samples may still be
loading), the script body, then the widget values, then `onLoad`, then
`onInit` — so `onInit` is the one place that sees the finished state, and
anything `onSave` carries is back before it runs. It is a callback, not a
delay: a `spawn` that waits a second before lifting the guard ignores the
player for that long on a fast machine and is still guessing on a slow one.
- **A mapping's layers are addressable per note.** Several articulations in one
`.dmap`, one `<layer>` each, and `playNote{dim1 = n}` picks one — nothing to
load in between, which is what makes a keyswitch instant instead of a reload.
The limit is worth knowing before you design around it: for a keygroup in
note-off trigger mode the engine synthesises the note-on itself, carrying
volume, pan, tune and the voice id but **not** the dimensions, so a release
layer is always layer zero of its own mapping.
- **An LFO's or step envelope's `Freq` is *synced* hertz.** With `SyncToHost`
on, the engine quantises the knob's travel onto its own ladder of note values
and prints the division; off, the same parameter is a frequency. A table of
divisions in the script is a second copy of that ladder, and the two disagree
the moment one of them is wrong. Bind the control and let the engine own both
the law and the readout.
- **A MIDI controller is not a `ControlSignalSource`.** `@MIDI CC 1` can be the
source of a connection, but it has no `.connections` for a script to ask, so a
route you want to switch on and off is easier to reach if the wheel writes a
macro and the macro is what the connection names. Then every modulator your
UI offers is an element and they are all found the same way.
- **The engine's own `Arpeggiator` can be remote-controlled.** Its `Mode`,
`Resolution` and `NumSteps` are parameters like any others, so a bank can put
one in the preset and let its interface drive it — twenty-eight orders, host
tempo and transport included, and no walk to write. Write your own step
sequencer only when you need what an arpeggiator does not have: a level and a
transposition per step, your own swing, a phrase bank saved with the preset.
## 12. When you are stuck
- **First, look at the example scripts** at
https://lua.uvi.net/_examples_page.html. They cover most common
patterns (arpeggiator, step sequencer, chord tools, harmonizer,
ensemble, strummer, …) with idioms that already handle the subtle
cases — held-note sets, shared coroutines, chord buffering, voice
tracking. Adapting one is almost always better than building from
scratch.
- For full signatures and parameter lists, fetch the relevant page from
https://lua.uvi.net rather than guessing.
- Prefer reading existing `.lua` files in this workspace for project-local
conventions before introducing new patterns.
This page is intentionally a summary. The authoritative documentation for every callback, widget, and engine parameter lives in the rest of this manual — see the Guides and API Quick Reference pages.