coloX System API
coloX system functions cover status queries, time and date, application management, data storage, service communication, and utilities.
Contents
- System status (stat)
- Status control (statctl)
- Time and date
- Application management
- Application data storage
- Background services
- Foreground/background switching
- Data utilities
- Debug output
- Internal functions
- Complete API index
1. System Status (stat)
stat(x) → value
Gets system status information.
Common arguments: (unlisted indices return 0)
| x | Returns | Description |
|---|---|---|
| 0 | number | Memory usage (KB) |
| 1 | number | Previous frame CPU utilization (0~1) |
| 2 | number | CPU usage (placeholder, currently always 0.5) |
| 4 | string | Clipboard contents (currently always empty) |
| 5 | number | Platform version (currently 14) |
| 6 | string | Application load parameters (PARAM_STR passed to load; desktop builds can specify them with -a) |
| 7 | number | Current frame rate (FPS) |
| 8 | number | Configured frame rate |
| 12 | number | Milliseconds since boot |
| 26 / 56 | number | Playback ticks in the current pattern |
| 89 | number, number | Device uptime in seconds (two values: integer and fractional parts) |
| 97 | number | Previous frame duration (seconds) |
| 100 | string | Breadcrumb string passed as the second argument to load (empty if omitted) |
| 108 | number | Always 32 |
| 9/10/11 | — | ESP32S3 firmware only: free heap / littlefs / TF card information (three return values each) |
Input state:
| x | Returns | Description |
|---|---|---|
| 30 | boolean | Whether keyboard data is available |
| 31 | string | Buffered keyboard data |
| 32 | number | Mouse/touch X position |
| 33 | number | Mouse/touch Y position |
| 34 | number | Mouse/touch button state |
Audio state:
| x | Returns | Description |
|---|---|---|
| 16..19 | number | SFX index playing on channels 0..3 |
| 20..23 | number | Note index on channels 0..3 (0..31) |
| 24 | number | Current playing pattern index |
| 25 | number | Total patterns played |
| 46..49 | number | SFX index playing on channels 0..3 |
| 50..53 | number | Note index on channels 0..3 |
| 54 | number | Current pattern index |
| 55 | number | Total patterns played |
| 56 | number | Playback ticks in the current pattern |
Local time:
| x | Returns | Description |
|---|---|---|
| 90 | number | Year |
| 91 | number | Month (1-12) |
| 92 | number | Day (1-31) |
| 93 | number | Hour (0-23) |
| 94 | number | Minute (0-59) |
| 95 | number | Second (0-59) |
| 96 | number | Weekday (1=Sunday .. 7=Saturday) |
-- Get the current time
local h = stat(93)
local m = stat(94)
local s = stat(95)
print(string.format("%02d:%02d:%02d", h, m, s))
-- Get the frame rate
local fps = stat(7)
print("FPS: " .. fps)
-- Get memory usage
local mem = stat(0)
print("Memory: " .. mem .. " KB")
2. Status Control (statctl)
statctl(key [, val]) → previous_value
Sets or queries system status. Pass val to set; omit it to query.
Available keys:
| key | Description |
|---|---|
altc | Alternate color (used by fill patterns in 32-bit color mode) |
tlmw | Map width mask for tline |
tlmh | Map height mask for tline |
tlmx | Map X offset for tline |
tlmy | Map Y offset for tline |
sprm | Sprite data address mapping (0x60 = use VRAM address) |
scrm | Screen data address mapping (0 = sprite sheet data; nonzero, default 0x60, = VRAM) |
mapw | Map width (0 = specification default) |
colm | Color mask: at 4bpp, low 4 bits write mask + high 4 bits read mask (blending effect); at 8bpp, combined 16-bit value (low byte write mask, high byte read mask, default 0xffff); at 16bpp, alpha blending parameter |
nedf | Round-screen display flags (round-screen firmware + 128-wide 4bpp cartridges only): bit0(1)=keep the image inside the circle (center within the inscribed square), bit1(2)=preserve aspect ratio, bit2(4)=disable scaling; commonly 1 or 3 (=1|2) |
dfps | Global FPS/CPU debug overlay (truthy=on / false or 0=off / omitted=query; off by default; persists across cartridge switches; FPS uses a short 15-frame average) |
Opus Codec Configuration (Firmware with Opus Enabled Only)
Opus encoder (oeXX, micpoll recording) and decoder (odXX, wave decoding) settings are independent. Changes affect the next lazily created codec; use orst to recreate existing codecs for changes to take effect.
Shared three-state convention:
- Query: omit
val, returning the current value. - Set: pass
val >= 0, applying it and returning the previous value. - Restore default: pass
val == -1, restoring the default and returning the previous value.
Encoder configuration (oeXX):
| key | Meaning | Valid values | Default |
|---|---|---|---|
oers | Sample rate (Hz) | 8000/12000/16000/24000/48000 | 16000 |
oedm | Frame duration (milliseconds) | 5/10/20/40/60 | 60 |
oebt | Bitrate (bit/s) | 0 = AUTO; otherwise a specific bitrate | 0 (AUTO) |
oecp | Complexity | 0–10 | 6 |
oeap | Application type | 0=VOIP / 1=AUDIO / 2=LOWDELAY | 0 (VOIP) |
Decoder configuration (odXX):
| key | Meaning | Valid values | Default |
|---|---|---|---|
odrs | Sample rate (Hz) | 8000/12000/16000/24000/48000 | 16000 |
oddm | Frame duration (milliseconds) | 5/10/20/40/60 | 60 |
Reset:
| key | Meaning | val |
|---|---|---|
orst | Destroy selected codecs; recreate with current cfg on next use | Omitted or -1=all / 0=encoder / 1=decoder |
Encoder/decoder sample rates and frame durations should match: recording uses
oeXX, playback usesodXX; both must agree to interoperate correctly.
-- Encode: 24kHz, 20ms frames, 24kbps, complexity 3 (save CPU)
statctl('oers', 24000)
statctl('oedm', 20)
statctl('oebt', 24000)
statctl('oecp', 3)
-- Decode: matching 24kHz, 20ms
statctl('odrs', 24000)
statctl('oddm', 20)
-- Query the current encoder frame duration
local dur = statctl('oedm')
-- Restore the default encoder complexity
statctl('oecp', -1)
-- Reset the codec so the changes above take effect immediately
statctl('orst') -- Both encoder and decoder
statctl('orst', 0) -- Reset the encoder only
statctl('orst', 1) -- Reset the decoder only
-- Set texture repetition parameters
statctl('tlmw', 8)
statctl('tlmh', 4)
-- Query current values
local w = statctl('tlmw')
3. Time and Date
time() → number
t() → number
Returns seconds elapsed since application startup.
Note: This is logical time computed from frames, not real-world time.
utcsec() → number
Returns seconds since 1970 in UTC (Unix timestamp). (Not recommended.)
utcdate(fmt [, sec]) → string
Formats time using a format string, similar to standard Lua os.date. (Not recommended.)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
fmt | string | "%c" | Time format; prefix ! forces UTC; "*t" returns a table with year/month/day/hour/min/sec/wday/yday/isdst |
sec | number | Current time | Unix timestamp |
-- Format the current time
local date_str = utcdate("%Y-%m-%d %H:%M:%S")
print(date_str)
-- Use a local-time value
local h = stat(93)
local m = stat(94)
local s = stat(95)
print(string.format("%02d:%02d:%02d", h, m, s))
4. Application Management
load(filename [, na [, param_str]])
Loads and switches to another application.
Parameters:
| Parameter | Description |
|---|---|
filename | Target application filename |
na | Breadcrumb (read through stat(100) in the new cartridge, e.g. for back navigation) |
param_str | Parameters passed to the new application (read with stat(6)) |
load("menu") -- Load the menu application
load("game", nil, "level=3") -- Load with parameters
run()
Restarts the current application from the beginning (no arguments accepted).
run() -- Restart
reload(dest, source, len [, filename])
Reloads application file data into memory. See memory.md.
reset()
Resets runtime state (palette, camera position, clipping region, and fill pattern to defaults).
reset() -- Reset all drawing state
5. Application Data Storage
Each application can have independent persistent storage of up to 1024 bytes (256 integers).
cartdata(id) → boolean
Declares and opens storage. Required before dget/dset. Repeated calls with the same key are harmless; calling again with a different key errors and returns to BIOS. false indicates failure to open.
Parameter: id — Storage name, at most 64 characters, uniquely identifying it. It is used directly as part of the storage filename; use safe characters such as letters, digits, and underscores.
cartdata("my_app_save")
dget(index) → number
Gets integer data at index, ranging 0..255.
dset(index, value [, flush])
Stores an integer at index.
Parameters:
| Parameter | Description |
|---|---|
index | Storage position 0..255 |
value | Integer value |
flush | true = save immediately to disk |
dflush()
Writes all unsaved data to disk immediately.
Note: Data is not saved automatically; unflushed changes are lost on reloading or switching applications. Either use
dset(index, value, true)for immediate persistence or explicitly calldflush()at key points (save menu, before exit).
-- Complete storage example
cartdata("high_score")
-- Read the high score
local best = dget(0)
if best == 0 then best = 0 end
-- Update the high score
function update_score(score)
if score > best then
dset(0, score, true) -- Save and write to disk immediately
best = score
end
end
6. Background Services
svcget(path [, filtervid]) → data [, vid, ttl]
Gets service data. path is a complete dot-separated path (e.g. "wifi.sta.ip"). A hit returns up to three values: data, version vid, and TTL.
Pass a known version as filtervid: if unchanged, returns only nil and that vid, enabling change detection. Omitting it always returns data.
svcadd(key [, vid], data) → boolean
Adds service data. key is a root key (replaces the whole root variable, without path semantics); optional vid is the data version (default 0). System service names starting with $ are unwritable (error). Returns true on success.
svcset(path, name, data) → boolean
Sets service data: assigns field name to data under path (dot-separated prefix). Paths starting with $ are unwritable (error). Returns true on success.
svcreq(type, name_path)
Makes a service request.
| Parameter | Description |
|---|---|
type | Request type (e.g. "http") |
name_path | Service path (e.g. "myservice.data") |
svcmon(name, path) → boolean
Watches service data changes through _svcind(seq, name, path) (seq comes from the event itself, not registration). Multiple paths can share a name; an empty path matches every event for that service. Returns true on success.
-- Register an HTTP request
local req = {
sn = 1, stat = 0,
url = "https://api.example.com/data",
method = 1,
headers = {["Content-Type"] = "application/json"},
reqdata = '{"key":"value"}'
}
svcset('testsvc', 'api', req)
svcreq("http", "testsvc.api")
-- Listen for service notifications
svcmon("http", "")
function _svcind(seq, name, path)
local data = svcget(name)
if data then
printh("Service data: " .. tostring(data))
end
end
7. Foreground/Background Switching
toidle([arg])
Switches the current application to idle (background). arg is forwarded to BIOS idle handling.
tofg([pri [, force]]) → boolean
Requests foreground (active) status for the application.
-- Switch to the background with a button
if btnp(5) then
toidle()
end
-- Return to the foreground with a button while idle
function _idle_update()
if btnp(5) then
tofg()
end
end
8. Data Utilities
compress(data [, from, to, level, ...]) → compressed, zlib_code
Compresses with zlib. from/to are a 1-based data range (all data by default); level is 0-9. Further optional parameters are advanced zlib options (method/windowBits/memLevel/strategy/dict). Returns compressed data and a zlib return code.
decompress(data [, from, to, ...]) → decompressed
Decompresses with zlib. Supports raw streams (negative windowBits) and dictionaries.
md5sum(data) → string
Computes the data's MD5 checksum.
md5sumhexa(data) → string
Computes MD5 and returns a hexadecimal string.
sha1sum(data) / sha1sumhexa(data) → string
Computes SHA-1 (20-byte binary / 40-character hexadecimal). For Base64, see b64encode/b64decode in lua.md.
local data = "hello world"
local compressed = compress(data)
local restored = decompress(compressed)
assert(restored == data)
local hash = md5sumhexa(data)
print("MD5: " .. hash)
9. Debug Output
printh(...)
Prints arguments to the host operating system console, similar to original Lua print, for debugging.
printh("Debug:", x, y, score)
10. Internal Functions
These double-underscore functions are for system internals or BIOS development; normal applications generally do not need them.
Application Management
| Function | Description |
|---|---|
__listcarts() | Get application list |
__getparams([del]) | Get application parameters; del=true clears them afterward |
__loadbioscart() | Load BIOS |
__loadprevcart() | Load the previous application, if any |
__loadsettingscart() | Load system settings menu |
__togglepausemenu([pause]) | Toggle pause menu (invert state without arguments) |
__resetcart() | Reload the current application |
Configuration Files
| Function | Description |
|---|---|
__cfgread(filename) | Read configuration file contents |
__cfgwrite(filename, str) | Write configuration file; true on success |
__cfgdel(filename) | Delete configuration file |
Other
| Function | Description |
|---|---|
__cartinfo(cartname) | Get cartridge information (size/filename/specid/ver/style/name/author/desc, etc.) |
__resread(name [, from, to]) | Read a resource; 'size' mode obtains its length first; supports 'fullpath' mode |
__reslist([pattern[, subdir[, type[, detail]]]]) | List resources: pattern accepts OR-separated patterns with '|', and '*'/'?' wildcards (e.g. '*.png|*.jpg', 'screen*.png'; no wildcard means exact filename; empty/nil means no filtering). subdir is relative to the cartridge directory; a leading / requests privileged full-path mode. type='dir'/'all' includes directories (files only by default). detail=true performs file stat to obtain size (omitted by default for performance). Returns records {name=name, path=relative path (directories end in /), type="file"/"dir", size=bytes (files only, with detail)}; path can be passed directly to __resread |
__getbioserror() | Get the latest load error |
usemod(modname) | Load optional modules ('mic'/'net'/'vg'/'sim'/'pad'/'padmag'/'b2d', depending on the device build) |
Globals
dofile/loadfileexist as unimplemented placeholders and error immediately; cartridges cannot load code from the filesystem (use#include/#blobfor embedded code).
anim(easing) andimg(image loading) are resident built-in modules, requiring nousemod;cjsonusesrequire(see lua.md).
11. Complete API Index
System Status
| Function | Description |
|---|---|
stat(x) | Get system status |
statctl(key [, val]) | Set/query system status |
Time
| Function | Description |
|---|---|
time() / t() | Application elapsed seconds (logical time) |
utcsec() | UTC Unix timestamp |
utcdate(fmt [, sec]) | Format time |
Application Management
| Function | Description |
|---|---|
load(filename [, na [, param]]) | Load an application |
run() | Restart (without arguments) |
reload(dest, src, len [, file]) | Reload data |
reset() | Reset drawing state |
Data Storage
| Function | Description |
|---|---|
cartdata(id) | Open storage |
dget(index) | Read data |
dset(index, value [, flush]) | Write data |
dflush() | Save to disk immediately |
Services
| Function | Description |
|---|---|
svcget(path [, filtervid]) | Get service data (may return data, vid, ttl) |
svcadd(key [, vid], data) | Add service data |
svcset(path, name, data) | Set service data |
svcreq(type, name_path) | Make a service request |
svcmon(name, path) | Watch service notifications |
Switching
| Function | Description |
|---|---|
toidle() | Switch to background |
tofg() | Request foreground |
Utilities
| Function | Description |
|---|---|
compress(data [, from, to, level, ...]) | zlib compression (returns compressed data, return code) |
decompress(data [, from, to, ...]) | zlib decompression |
md5sum(data) | MD5 checksum |
sha1sum(data) / sha1sumhexa(data) | SHA-1 digest (binary / hexadecimal) |
md5sumhexa(data) | MD5 hexadecimal |
printh(...) | Debug printing |
usemod(name) | Load an optional module |