Skip to main content

coloX System API

coloX system functions cover status queries, time and date, application management, data storage, service communication, and utilities.


Contents​

  1. System status (stat)
  2. Status control (statctl)
  3. Time and date
  4. Application management
  5. Application data storage
  6. Background services
  7. Foreground/background switching
  8. Data utilities
  9. Debug output
  10. Internal functions
  11. Complete API index

1. System Status (stat)​

stat(x) → value​

Gets system status information.

Common arguments: (unlisted indices return 0)

xReturnsDescription
0numberMemory usage (KB)
1numberPrevious frame CPU utilization (0~1)
2numberCPU usage (placeholder, currently always 0.5)
4stringClipboard contents (currently always empty)
5numberPlatform version (currently 14)
6stringApplication load parameters (PARAM_STR passed to load; desktop builds can specify them with -a)
7numberCurrent frame rate (FPS)
8numberConfigured frame rate
12numberMilliseconds since boot
26 / 56numberPlayback ticks in the current pattern
89number, numberDevice uptime in seconds (two values: integer and fractional parts)
97numberPrevious frame duration (seconds)
100stringBreadcrumb string passed as the second argument to load (empty if omitted)
108numberAlways 32
9/10/11—ESP32S3 firmware only: free heap / littlefs / TF card information (three return values each)

Input state:

xReturnsDescription
30booleanWhether keyboard data is available
31stringBuffered keyboard data
32numberMouse/touch X position
33numberMouse/touch Y position
34numberMouse/touch button state

Audio state:

xReturnsDescription
16..19numberSFX index playing on channels 0..3
20..23numberNote index on channels 0..3 (0..31)
24numberCurrent playing pattern index
25numberTotal patterns played
46..49numberSFX index playing on channels 0..3
50..53numberNote index on channels 0..3
54numberCurrent pattern index
55numberTotal patterns played
56numberPlayback ticks in the current pattern

Local time:

xReturnsDescription
90numberYear
91numberMonth (1-12)
92numberDay (1-31)
93numberHour (0-23)
94numberMinute (0-59)
95numberSecond (0-59)
96numberWeekday (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:

keyDescription
altcAlternate color (used by fill patterns in 32-bit color mode)
tlmwMap width mask for tline
tlmhMap height mask for tline
tlmxMap X offset for tline
tlmyMap Y offset for tline
sprmSprite data address mapping (0x60 = use VRAM address)
scrmScreen data address mapping (0 = sprite sheet data; nonzero, default 0x60, = VRAM)
mapwMap width (0 = specification default)
colmColor 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
nedfRound-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)
dfpsGlobal 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):

keyMeaningValid valuesDefault
oersSample rate (Hz)8000/12000/16000/24000/4800016000
oedmFrame duration (milliseconds)5/10/20/40/6060
oebtBitrate (bit/s)0 = AUTO; otherwise a specific bitrate0 (AUTO)
oecpComplexity0–106
oeapApplication type0=VOIP / 1=AUDIO / 2=LOWDELAY0 (VOIP)

Decoder configuration (odXX):

keyMeaningValid valuesDefault
odrsSample rate (Hz)8000/12000/16000/24000/4800016000
oddmFrame duration (milliseconds)5/10/20/40/6060

Reset:

keyMeaningval
orstDestroy selected codecs; recreate with current cfg on next useOmitted or -1=all / 0=encoder / 1=decoder

Encoder/decoder sample rates and frame durations should match: recording uses oeXX, playback uses odXX; 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:

ParameterTypeDefaultDescription
fmtstring"%c"Time format; prefix ! forces UTC; "*t" returns a table with year/month/day/hour/min/sec/wday/yday/isdst
secnumberCurrent timeUnix 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:

ParameterDescription
filenameTarget application filename
naBreadcrumb (read through stat(100) in the new cartridge, e.g. for back navigation)
param_strParameters 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:

ParameterDescription
indexStorage position 0..255
valueInteger value
flushtrue = 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 call dflush() 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.

ParameterDescription
typeRequest type (e.g. "http")
name_pathService 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​

FunctionDescription
__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​

FunctionDescription
__cfgread(filename)Read configuration file contents
__cfgwrite(filename, str)Write configuration file; true on success
__cfgdel(filename)Delete configuration file

Other​

FunctionDescription
__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/loadfile exist as unimplemented placeholders and error immediately; cartridges cannot load code from the filesystem (use #include/#blob for embedded code).

anim (easing) and img (image loading) are resident built-in modules, requiring no usemod; cjson uses require (see lua.md).


11. Complete API Index​

System Status​

FunctionDescription
stat(x)Get system status
statctl(key [, val])Set/query system status

Time​

FunctionDescription
time() / t()Application elapsed seconds (logical time)
utcsec()UTC Unix timestamp
utcdate(fmt [, sec])Format time

Application Management​

FunctionDescription
load(filename [, na [, param]])Load an application
run()Restart (without arguments)
reload(dest, src, len [, file])Reload data
reset()Reset drawing state

Data Storage​

FunctionDescription
cartdata(id)Open storage
dget(index)Read data
dset(index, value [, flush])Write data
dflush()Save to disk immediately

Services​

FunctionDescription
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​

FunctionDescription
toidle()Switch to background
tofg()Request foreground

Utilities​

FunctionDescription
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