How a script runs
The three functions
Section titled “The three functions”A script is a Lua file. When it arrives, the panel runs it from top to bottom once. That is when your functions and variables get defined. Then it calls three functions by name, if you defined them:
| Function | When | Use it for |
|---|---|---|
_init() |
Once, right after the file has run | Setting up state, building meshes and textures |
_update(dt) |
Every frame | Moving things. dt is seconds since the last frame |
_draw() |
Every frame, after _update |
Drawing |
All three are optional. A script with only _draw is fine.
local stars = {}
function _init() for i = 1, 20 do stars[i] = { x = math.random(0, 63), y = math.random(0, 63), speed = math.random(5, 30) } endend
function _update(dt) for _, s in ipairs(stars) do s.x = s.x - s.speed * dt if s.x < 0 then s.x = 63 end endend
function _draw() gfx.cls() for _, s in ipairs(stars) do gfx.pset(math.floor(s.x), s.y, 255, 255, 255) endendOne frame
Section titled “One frame”Every frame the panel does this, about 30 times a second:
- Clears the canvas to black.
- Calls
_update(dt). - Calls
_draw(). - Copies the canvas to the LEDs.
Two consequences:
- You draw the whole picture every frame. Nothing from the previous frame is left over, so there is no need to erase where something used to be.
- Drawing in
_initdoes nothing. The canvas is cleared before the first frame.
If a frame takes a long time, dt is capped at 0.25 seconds, so a stall does not make everything jump.
What a script can use
Section titled “What a script can use”Scripts run in a sandbox. They have:
- The Lua 5.4 standard libraries
string,table,math,utf8andcoroutine, and the basic functions (pairs,ipairs,tostring,pcall, and so on). gfxfor drawing,mat4for 3D math,gmathfor noise, and theuniformstable. These are described in the following pages.print(...), which writes to the panel’s serial port, where you need a USB cable to read it. In the preview it appears in the console under the picture.
They do not have files, the network, the clock, or a way to load more code: io, os, debug, require, load and dofile are not there.
Limits
Section titled “Limits”| Limit | Value | What happens when you pass it |
|---|---|---|
| Script size | 24 KB | The editor refuses to upload it |
| Memory | 512 KB | The script stops with “not enough memory” |
| Work per frame | 2,000,000 Lua instructions | The script stops with an instruction budget error |
The instruction limit is what stops an accidental infinite loop from freezing the panel. A normal script uses a small fraction of it. The full list is on the Limits page.
Next: Drawing.