Skip to main content

coloX Lua Language

coloX uses a customized Lua 5.4. This document describes its differences from standard Lua 5.4.


Contents​

  1. Language customization
  2. Lexical extensions
  3. String escape patches
  4. Standard library support
  5. Extension libraries and functions

1. Language Customization​

FeatureDescription
Unicode variable namesUnicode characters, including Chinese, are allowed in variable names
Float-to-integer conversionAutomatically takes floor where an integer is required, instead of raising an exception
Lua 5.3 compatibilityCompatible with some Lua 5.3 syntax and behavior
32-bit numbersUses 32-bit integers and 32-bit floating-point numbers
-- Unicode variable names (Chinese identifiers are intentional)
local 分数 = 100 -- Unicode identifier meaning score
local 名称 = "测试" -- Unicode identifier and string meaning name and test

-- Floating-point API arguments are rounded down automatically (without an error)
pset(3.7, 2.2, red) -- Actually draws at (3, 2)

-- Table indices are unaffected and retain standard Lua semantics
local arr = {}
arr[3.7] = "ok" -- 3.7 is a distinct float key (arr[3] remains nil)

2. Lexical Extensions​

Binary number literals starting with 0b or 0B are supported:

local a = 0b1101       -- Binary 1101 = 13
local b = 0B11001100 -- Binary 11001100 = 204
local c = 0b1010 + 5 -- 10 + 5 = 15

3. String Escape Patches​

coloX extends Lua string escapes; these characters serve as control instruction prefixes in print:

EscapeEquivalentDescription
\*\1Character repetition prefix
\#\2Background color setting
\-\3Horizontal cursor movement
\|\4Vertical cursor movement
\+\5Diagonal cursor movement
\^\6Special instruction prefix

These escapes underpin the control syntax of print; see escape sequences in text.md.


4. Standard Library Support​

coloX uses customized Lua 5.4 (32-bit numeric mode: LUA_INTEGER is a signed 32-bit integer and LUA_NUMBER is a 32-bit float, with only 7 significant digits).

Available Lua Standard Libraries​

LibraryDescription
_G (base)Basic functions (assert/error/pcall/xpcall/pairs/ipairs/select/type/tostring/tonumber/setmetatable/getmetatable/rawget/rawset/rawequal/rawlen/next/warn, etc.). Note that print is overridden by coloX's screen drawing function; use printh for console output
coroutineCoroutine support (complete 5.4 set, including close and isyieldable)
tableconcat/insert/remove/move/pack/unpack/sort
stringComplete 5.4 set (see below, including the string.pack family)
mathComplete 5.4 set (including tointeger/type/maxinteger/mininteger), plus atan2/pow/log10/frexp/ldexp/cosh/sinh/tanh retained for 5.3 compatibility
utf8UTF-8 support (see below)
debugDebugging library (all 17 entries, including traceback/getinfo)
packageThe require mechanism (see below)

There are also 25 convenient global math functions (max/min/mid/flr/cos/sin/atan2/band/bor/bxor/bnot/shl/shr/lshr/rotl/rotr/sgn/tostr/tonum/chr/ord/split, etc.), coexisting separately with math.*; see math.md.

The string Library and string.pack Binary Packing​

string is the complete standard implementation: byte/char/dump/find/format/gmatch/gsub/len/lower/match/rep/reverse/sub/upper, plus the binary packing suite pack/unpack/packsize—no manual bit shifting is needed to parse binary protocols (network packets or file formats):

-- Pack: protocol header = magic (2 bytes) + version (1 byte) + length (4 bytes, little-endian)
local bin = string.pack("<I2 B I4", 0xA55A, 3, 128)
-- string.packsize("<I2 B I4") → 7 (i[n]/I[n] are fixed-width with no alignment padding)

-- Unpack
local magic, ver, len = string.unpack("<I2 B I4", bin)

Format quick reference (full rules: Lua 5.4 manual §6.4.2):

FormatDescription
b/B h/H l/L j/JSigned/unsigned integers (1/2/4/integer-width bytes)
i[n] / I[n]n-byte integer (native int when n is omitted; 4 bytes on this platform)
f4-byte float (float32, matching this platform's number)
d8-byte double (note: number itself has only float32 precision, so passing through double loses precision)
nThis platform's lua_Number (float32)
s[n] / z / c nLength-prefixed / zero-terminated / fixed-length string
x / XPadding byte / alignment padding
< / > / =Little-endian / big-endian / native byte order
!nMaximum alignment (native alignment by default)

Integer sizes are limited to 16 bytes; alignment must be a power of 2. In 32-bit integer mode, j/J and lua_Number are 4 bytes.

The utf8 Library​

Complete standard set: utf8.char(...), utf8.codepoint(s [, i [, j]]), utf8.len(s [, i [, j]]), utf8.offset(s, n [, i]), utf8.codes(s) (iterator), and constant utf8.charpattern ("[\0-\x7F\xC2-\xFD][\x80-\xBF]*").

-- Iterate over each Unicode code point in a string
for p, cp in utf8.codes("你好 world") do -- Intentional Chinese text for the UTF-8 example
printh(string.format("%d: U+%04X", p, cp))
end

-- Truncate Chinese text by display width (CJK characters occupy 2 columns)
local function utf8_width(s)
local w = 0
for _, cp in utf8.codes(s) do
w = w + (cp > 0x2E80 and 2 or 1)
end
return w
end

Convert GB2312 strings to UTF-8 with global gb2312_to_utf8() before processing with utf8 (see text.md).

package and require​

require is available, but cartridges have no general-purpose filesystem: only modules preloaded by the host are available—require("cjson") and require("cjson_safe"). Requiring an unknown module raises module not found. Reuse cartridge code with the #include preprocessor directive (compile-time concatenation; see getting_started.md).

Unavailable Features​

FeatureDescription
load()Renamed to loads() (loads a code chunk from a string/reader function; direct functions or #include are recommended inside cartridges)
loadstring()Absent (removed in 5.4 and not restored)
dofile() / loadfile()Globals exist as error placeholders and throw immediately; code cannot be loaded from the filesystem
os libraryUnavailable; use stat(90..96) for time
io libraryUnavailable (use the resource mechanism for file access: __resread/__reslist; see system.md)
file operationsUnavailable

About "Lua 5.3 Compatibility"​

The compatibility layer restores only a few features: deprecated math functions (atan2/pow, etc.) and emulation of <= with __lt when __le is absent. Behaviors from 5.3/5.2 such as loadstring, math.mod, and table.getn are not restored.


5. Extension Libraries and Functions​

cjson / cjson_safe​

JSON encoding/decoding library, available after require. For complete type mappings, configuration, and limitations, see cjson.md.

local json = require("cjson")

-- Encode
local data = {name = "test", value = 42}
local str = json.encode(data)

-- Parse
local obj = json.decode('{"key":"value","num":123}')
print(obj.key) -- → "value"

-- Decode safely (without throwing)
local json_safe = require("cjson_safe")
local obj, err = json_safe.decode(invalid_str)
if not obj then
printh("JSON error: " .. tostring(err))
end

compress(str, from, to, compresslvl [, method, windowBits, memlvl, strategy, dict])​

zlib compression function.

Parameters:

ParameterDescription
strString to compress
from, toData range
compresslvlCompression level (0-9)
method, windowBits, memlvl, strategy, dictOptional zlib parameters

decompress(zstr, from, to [, windowBits, dict])​

zlib decompression function.

md5sum(str) → string​

Computes an MD5 checksum, returning 16 bytes of binary data.

md5sumhexa(str) → string​

Computes an MD5 checksum, returning a lowercase hexadecimal string.

local hash = md5sumhexa("hello world")
-- → "5eb63bbbe01eeed093cb22bb8f5acdc3"

b64encode(data) / b64decode(data)​

Base64 encoding/decoding (C implementation, safe for arbitrary binary strings). b64decode returns nil,"EB64" for invalid input.

b64encode("hello world")          -- "aGVsbG8gd29ybGQ="
b64decode("aGVsbG8gd29ybGQ=") -- "hello world"

sha1sum(data) / sha1sumhexa(data)​

Computes a SHA-1 digest: sha1sum returns a 20-byte binary string; sha1sumhexa returns 40 lowercase hexadecimal characters.

sha1sumhexa("abc")
-- → "a9993e364706816aba3e25717850c26c9cd0d89d"

API Index​

Function/libraryDescription
loads(chunk [, chunkname [, mode [, env]]])Load a code chunk from a string/reader (formerly load)
require(modname)Load a preloaded module (cjson/cjson_safe)
utf8.*UTF-8 processing (char/codepoint/len/offset/codes/charpattern)
string.pack/unpack/packsizePack/unpack binary data
cjsonJSON encoding/decoding library (see cjson.md)
cjson_safeSafe JSON encoding/decoding (returns nil, err without throwing)
compress(str, ...)zlib compression
decompress(zstr, ...)zlib decompression
md5sum(str)MD5 checksum (binary)
md5sumhexa(str)MD5 checksum (hexadecimal)
b64encode(data) / b64decode(data)Base64 encoding/decoding (decode returns nil,"EB64" for invalid input)
sha1sum(data) / sha1sumhexa(data)SHA-1 digest (binary / hexadecimal)