Skip to content

How a script runs

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) }
end
end
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
end
end
function _draw()
gfx.cls()
for _, s in ipairs(stars) do
gfx.pset(math.floor(s.x), s.y, 255, 255, 255)
end
end

Every frame the panel does this, about 30 times a second:

  1. Clears the canvas to black.
  2. Calls _update(dt).
  3. Calls _draw().
  4. 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 _init does 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.

Scripts run in a sandbox. They have:

  • The Lua 5.4 standard libraries string, table, math, utf8 and coroutine, and the basic functions (pairs, ipairs, tostring, pcall, and so on).
  • gfx for drawing, mat4 for 3D math, gmath for noise, and the uniforms table. 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.

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.