uvi-script
Musical event scripting with Lua
Lua Language Reference

Overview

uvi-script is built on the Lua programming language, a lightweight, fast, and embeddable scripting language. Understanding Lua is essential for writing effective uvi-scripts.

This page covers the Lua-specific aspects of uvi-script: which version is used, what libraries are available, and the real-time constraints that shape how you write scripts.


Learning Lua

If you're new to Lua or need a reference, we recommend these excellent resources:

These resources are well-written and provide a solid foundation for scripting. Using a simple, widespread, yet powerful scripting language that can be learned online was one of the main motivations for choosing Lua.

What you need to know:

  • Basic syntax (variables, functions, tables, control structures)
  • Tables (Lua's primary data structure)
  • Functions and closures
  • Local vs global variables (critical for uvi-script!)
  • Coroutines (used internally for threading)

The Lua Virtual Machine

uvi-script uses a sandboxed Lua 5.1 virtual machine with custom extensions designed for real-time audio processing.

Real-Time Execution Constraints

Most script code executes with real-time priority to ensure sample-accurate timing and low-latency performance. This places specific constraints on what you can do:

Real-Time Requirements:

  • Predictable execution time - Code must complete within a bounded time
  • Bounded memory allocation - Allocations are served from a real-time memory pool, not the system allocator. Creating tables and strings is allowed (the API itself does it, e.g. playNote copies its event table), but keep them small and preallocate what you can
  • No blocking operations - Cannot wait on external resources (files, network, etc.)
  • Bounded loops - Avoid lengthy operations like iterating over large tables (10000+ entries)

Exceptions (Non-Real-Time): These callbacks run with relaxed constraints and can allocate memory:

  • Main script chunk (executed once at load time)
  • onLoad - Called when restoring saved state
  • onSave - Called when saving state

Memory Management

To maintain real-time safety, uvi-script uses a pre-allocated memory pool for all Lua operations during real-time execution.

Best Practices:

  • Pre-allocate tables in the main chunk rather than in callbacks
  • Reuse tables instead of creating new ones in loops
  • Use local variables for temporary data (faster and doesn't allocate)
  • Avoid string concatenation in tight loops (creates new strings)

Language and memory limits

The compiler is the standard Lua 5.1.4 one, unmodified, so its fixed limits apply as they are. Small scripts never meet them; a large instrument script, or one ported line for line from a language where every variable is declared up front, can.

Compiler limits

limit applies to error message
200 active local variables each function, the main chunk included main function has more than 200 local variables or function at line N has more than 200 local variables
60 upvalues each function function at line N has more than 60 upvalues
250 registers each function ‘function or expression too complex near ’...'\ilinebr </td> </tr> <tr class="markdownTableRowEven"> <td class="markdownTableBodyNone"> 200 nesting levels \ilinebr </td> <td class="markdownTableBodyNone"> the whole chunk \ilinebr </td> <td class="markdownTableBodyNone">chunk has too many syntax levels`

What counts as a local:

  • every top-level local x and local function f of the script counts against the main chunk, and each name of a local a, b, c counts separately;
  • a function's parameters count in that function;
  • a numeric for adds three hidden variables plus its loop variable, a generic for three hidden ones plus its variables — while the loop is open;
  • globals do not count at all.

The limit is on locals active at the same time: a local declared inside a do … end block, or inside a loop body, stops counting at the block's end.

The upvalue limit is the one a callback meets. Every top-level local that onNote, a widget's changed handler or any other function refers to is one of its upvalues, so a callback that touches more than 60 distinct top-level locals fails to compile even when the chunk as a whole is under 200. The register limit usually shows up in the same scripts: with close to 200 locals in scope, little room is left for the temporaries of a long expression or a call with many arguments.

The message is prefixed with the usual chunk:line: location, and that line is where the limit was crossed — the declaration of the 201st local, the use of the 61st upvalue. The N inside the message is different: it is the line where the offending function starts. Neither message has a near part; Lua 5.1 reports these limits without pointing at a token.

Where the error points

A compile error names the script as its chunk, then the line:

  • a script loaded from a file is named by its path: /path/to/script.lua:12: …;
  • a script embedded in the program is named by its own first line: [string "--------------------------------..."]:12: ….

The second form looks like a quoted fragment of code, and it is: Lua labels an embedded chunk with the start of its source, and most scripts start with a comment banner. The number after it is still the line in the script.

Checking the headroom

There is no built-in counter. For the main chunk, counting top-level declarations is a good estimate when the script is indented conventionally:

grep -cE '^local ' script.lua

counts the lines that start with local at the first column. Add one for every extra name on a local a, b, c line; declarations inside a top-level for or do block are indented and correctly left out. For an exact answer, append a throw-away local line with a known number of names at the end of the script: if it still loads, at least that many slots were free.

Staying under the limits

  • Group related values into tables. A table is one local and, from a callback, one upvalue, however many fields it has:

    -- 3 locals, and 3 upvalues for any callback that uses them all
    local ATTACK, DECAY, RELEASE = 10, 200, 500
    -- 1 local, 1 upvalue
    local ENV = { attack = 10, decay = 200, release = 500 }

    Widgets can be grouped the same way — ui.cutoff = Knob{…} rather than one local per knob.

  • Wrap one-shot setup code in do … end, or move it into a function that is called once: the locals it needs stop counting when the block ends.
  • Keep what callbacks share in few tables, so the upvalue count of each callback stays small.
  • Merging duplicate constants only helps when each one was its own local.

Allocation size

No single allocation above about 1 MB can succeed in the script's Lua heap. When one is attempted Lua raises not enough memory, and the console and the log show an out-of-memory error. In practice that caps:

  • any single string at about 1 MB — including the JSON the engine builds from the table onSave returns, so the whole saved state of a script has to stay under it;
  • the source of a script embedded in a program at about 1 MB.

Many small tables and strings are not affected; the limit is on one block, not on the total.

Widgets, parameters and automation

The script side sets no limit on the number of widgets or parameters. Host automation does: Falcon has 128 host automation slots, shared by the whole plugin instance — every script and every exported parameter in it. Once they are all taken, setting exported on another widget reports an error in the console, and that parameter is not automatable. See Parameter Export.


Available Standard Libraries

uvi-script provides access to a subset of Lua's standard libraries. Libraries that require operating system access or blocking I/O are not available to maintain real-time safety.

Available Libraries

base - Basic Functions

  • Core functions: assert, error, pcall, type, tonumber, tostring
  • Table/iteration: pairs, ipairs, next
  • Utility: print, select, unpack

package - Module System

  • require - Load Lua modules
  • Note: Only Lua modules can be loaded, not C libraries

table - Table Manipulation

  • table.insert, table.remove
  • table.concat
  • table.sort
  • table.copy(t) - uvi-script extension: creates a shallow copy of a table
  • Note: Be mindful of performance on large tables in real-time code

string - String Operations

  • string.sub, string.find, string.match
  • string.format, string.gsub
  • Pattern matching (Lua patterns, not full regex)

math - Mathematical Functions

  • Trigonometry: math.sin, math.cos, math.tan, math.asin, etc.
  • Utilities: math.abs, math.floor, math.ceil, math.min, math.max
  • Random: math.random, math.randomseed
  • Constants: math.pi, math.huge

bit - Bitwise Operations

  • Lua 5.1 has no native bitwise operators; this library provides them
  • bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift

class - Object-Oriented Programming

Not Available (Real-Time Safety)

os - Operating System Facilities

  • Not available: Would break real-time guarantees
  • Reasons: Blocking system calls, unpredictable timing

io - File I/O

  • Not available: Would block real-time thread
  • Alternative: Use asynchronous API for file operations

coroutine and debug

  • Not available: the coroutine and debug globals are removed after the runtime has loaded
  • Reasons: the runtime drives every callback as a coroutine under its own scheduler; resuming or yielding coroutines yourself would break it
  • Alternative: use spawn, run, wait and waitBeat for cooperative threading
  • Note: the tables are hidden, not unloaded, so require "coroutine" still returns them; do not use it

Third-Party Lua Libraries

  • Not allowed: Cannot load external C libraries or most Lua libraries
  • Reasons: Real-time safety, memory allocation, security
Note
For file I/O and other blocking operations, use the asynchronous API which runs on background threads and safely communicates results back to your script.

Built-in Overrides and Utility Globals

The runtime replaces a few base library functions with script-friendly versions and adds several global helpers.

Printing

print(...) writes to the script console, not to a standard output stream. Arguments are converted to text and separated by single spaces (the standard print separates them with tabs). Event tables — tables carrying a numeric type field, such as the argument of onNote — are expanded to their key=value contents instead of being shown as a table address. Errors (syntax errors at load time, runtime errors in callbacks) are shown in the same console with their file and line number, and are also appended to ScriptProcessor.log (macOS: ~/Library/Logs/<host>/ScriptProcessor.log, Windows: APPDATA%\<host>\ScriptProcessor.log); print output goes to the console only:

print("velocity:", 100) -- velocity: 100
print({type=Event.NoteOn, note=60, velocity=100}) -- note=60 velocity=100 type=144 (field order may vary)
Event types.
Definition Engine.cpp:905

Other tables print as an address, like with the standard print; use the helpers below to display their contents.

print_table(t, printer, indent) prints one key:value line per entry and recurses into nested tables, indenting each nesting level by two extra spaces. printer (optional) is the output function, print by default; indent (optional) is the initial indentation string. Values that are not booleans, numbers, or strings are shown by their type name.

table.tostring(t) returns the top-level key=value pairs of a table as a single space-separated string. Pairs appear in unspecified order and nested tables appear as addresses.

table.print(t) prints table.tostring(t) wrapped in braces. Does nothing if t is not a table.

Table copying

table.copy(t) returns a new table with the same keys and values. The copy is shallow: nested tables are shared with the original, not duplicated.

Assertions and warnings

assert(cond, msg, level) raises an error with message msg (default "error") when cond is false or nil. Unlike the standard assert, it takes a third level argument selecting the stack level at which the error is reported: 1 (the default) blames the caller of assert, 2 blames the caller's caller, and so on — useful for reporting argument errors at the call site of your own functions. Also unlike the standard version, it does not return its arguments on success.

warning(condition, msg, level) has the same signature but never raises an error: when condition is false it prints msg prefixed with warning: [file]:line, where the location is taken from the stack level selected by level (default 1, the caller of warning).

function setVolume(v)
assert(type(v) == "number", "v should be a number", 2) -- reported at the caller of setVolume
warning(v <= 1, "volume above 1 will clip")
end

Object-Oriented Programming

uvi-script includes a built-in class system. Use class to define classes with constructors, methods, and instance state. This is useful for encapsulating complex logic like sequencers, state machines, or multi-voice managers.

Defining a Class

class 'NoteTracker'
function NoteTracker:__init()
self.voices = {}
end
function NoteTracker:add(note, id)
self.voices[note] = id
end
function NoteTracker:remove(note)
self.voices[note] = nil
end
function NoteTracker:forEach(fn)
for note, id in pairs(self.voices) do
fn(note, id)
end
end

Create instances with the class name as a function call:

local tracker = NoteTracker()
function onNote(e)
local id = postEvent(e)
tracker:add(e.note, id)
end
function onRelease(e)
tracker:remove(e.note)
end
function onPitchBend(e)
tracker:forEach(function(note, id)
changeTune(id, e.bend * 2)
end)
end
void onNote(table e)
event callback that will receive all incoming note-on events if defined.
void onPitchBend(table e)
event callback that will receive all incoming pitch-bend events if defined.
void onRelease(table e)
event callback executed whenever a note off message is received.
function postEvent(e, delta)
send a script event back to the script engine event queue.
Definition api.lua:959
function changeTune(voiceId, shift, relative, immediate)
change the tuning of a specific voice in (fractional) semitones.
Definition api.lua:567

Engine Objects

The synthesis engine objects (Program, Layer, Keygroup, Oscillator, etc.) are C++ objects exposed to Lua. They support the same colon method syntax:

local osc = Program.layers[1].keygroups[1].oscillators[1]
osc:setParameter("Gain", 0.5) -- method call
local info = osc.sampleInfo -- property access
print(info.name, info.duration)
A Patch that represents a monotimbral instrument.
Definition Engine.cpp:350
table layers
Layer list for this Program (1-indexed, use #Program.layers to get the count)
Definition Engine.cpp:359

Threading and Coroutines

uvi-script uses Lua coroutines internally to implement its cooperative threading model. Each event callback (onNote, onRelease, etc.) runs as a separate coroutine that can be suspended using wait, waitBeat, or waitForRelease.

What you need to know:

  • Each callback is an independent thread (coroutine)
  • Threads are cooperative - they must explicitly yield using wait() functions
  • Local variables in callbacks are thread-local
  • Global variables are shared across all threads

For detailed information about threading and timing, see Threading and Timing.


See Also