coloX Gamepad API
Gamepads (including Bluetooth gamepads) use an input channel independent of btn(). Onboard buttons work as before;
the two do not interfere with each other.
Currently supports up to 2 players. Device support varies; check the return value of usemod.
Two modules, enabled as needed:
| Module | Contents | Usage |
|---|---|---|
pad | Read buttons / sticks / connection state | Game cartridges |
padmag | Scan / pair / connect / disconnect | Management interfaces such as pairing screens |
They are separate because their lifecycles differ completely: state is read every frame, while management primitives are needed only for pairing. Normal cartridges should not add a dozen management functions to the global table just to play a game.
Contents
- Enabling the gamepad API
- Reading buttons
- Reading sticks
- Player numbers and connection state
- Gamepad management (scan / pair / disconnect)
- Complete API index
- Relationship to
btn()
1. Enabling the Gamepad API
function _init()
-- During gameplay: read state
if usemod('pad') then
haspad = true
end
-- Needed only for a pairing interface:
-- if usemod('padmag') then ... end
end
The modules are independent; their functions exist only after each returns true (pad also provides the PAD constants table).
Unsupported devices return an empty/falsy value; those names are absent from the global table, so direct calls raise errors. Always check the return value, rather than assuming success.
The names also do not exist before enabling the module; cartridges without gamepad needs get no unnecessary globals.
2. Reading Buttons
pad_state([p]) → bitmask
Returns the bitmask of buttons currently held by a player.
| Parameter | Type | Description |
|---|---|---|
p | number | Player number (0 or 1); defaults to 0 |
Use with PAD constants in bitwise operations:
local s = pad_state(1)
if s & PAD.A ~= 0 then
-- Player 2 is holding A
end
pad_btn(id [, p]) → boolean
Checks whether a particular button is pressed. Pass a constant from PAD as id.
if pad_btn(PAD.START, 0) then start_game() end
About "Newly Pressed"
Gamepads provide held states only: pad_btn stays true while held; there is no newly-pressed-this-frame variant.
For edges, remember the previous frame yourself:
local prev = 0
function _update()
local now = pad_state(0)
local pressed = now & ~prev -- Buttons newly pressed this frame
if pressed & PAD.A ~= 0 then fire() end
prev = now
end
Rationale: Gamepad press/release may bounce; deciding when a press counts as new is better left to the cartridge than standardized by the runtime.
3. Reading Sticks
pad_stick([p]) → lx, ly, rx, ry
Returns four values: left stick x/y and right stick x/y.
0 means centered. With no gamepad, or no sticks on that gamepad, all values are 0 (centered).
local lx, ly = pad_stick(0)
if lx < 0 then move_left() elseif lx > 0 then move_right() end
The stick value range is not final. Use signs and relative magnitudes for now; avoid fixed thresholds.
4. Player Numbers and Connection State
pad_conn([p]) → boolean
Whether that player slot has a gamepad this frame.
⚠ A single connected gamepad is player 0. Gamepads take the lowest free slot:
- One connected → slot 0 (the
btn()channel); player 1 does not exist then - Two connected → players 0 and 1
For two-player cartridges, do not assume the gamepad in your hand is player 1; check pad_conn(0) / pad_conn(1).
Out-of-Range and Disconnected Players
For out-of-range player numbers or empty slots, read functions return false / 0 / all-zero sticks,
without errors, so unconditional reads are safe.
5. Gamepad Management (Scan / Pair / Disconnect)
Every function in this section requires usemod('padmag') first (not usemod('pad')).
These functions are for pairing interfaces. Paired gamepads reconnect automatically; ordinary cartridges need not manage this.
A pairing interface usually enables both modules: padmag manages devices and pad reads pad_conn() for live status:
local hasmag = usemod('padmag') -- pad_scan / pad_bonds / ... (nil if unsupported)
local haspad = usemod('pad') -- pad_conn / pad_state / ...
All calls return immediately; slow work (scanning/connecting) runs asynchronously in the background. Poll query functions for progress.
On unsupported devices (without gamepad firmware / in desktop builds), functions return safe values
(false / 0 / empty table / empty string); pad_scanstate() is always 0, without errors.
★ Indices start at 0: idx for pad_connect / pad_unpair is 0-based,
unlike 1-based ipairs. Pass i-1 when iterating a list (example below).
Scanning (Asynchronous)
Scanning takes seconds; the cartridge must not wait blocked. Use start → poll:
pad_scan([sec]) → boolean
Starts a background scan and returns immediately.
| Parameter | Type | Description |
|---|---|---|
sec | number | Scan duration in seconds, valid range 1..60; omitted/out-of-range uses 8 seconds |
true = request accepted (not scan complete); false = rejected because the Bluetooth stack is down,
or scanning/connecting is in progress (retry later). An already connected gamepad is not busy;
pairing a second gamepad naturally requires scanning while one is connected.
Results from the previous scan are cleared when scanning starts. If a gamepad connects by itself during scanning, the scan ends early (yielding to the connection) while retaining discovered results.
Scanning does not connect automatically:
pad_scanonly populates results; the user selects a device withpad_connect. However, the engine has a background automatic flow not controlled by parameters, determined by whether the pairing list is empty:
- No pairing records at all: when idle, it scans and automatically connects to the first device whose name resembles a gamepad (recording the pairing on success); if none is found, it rescans after a few seconds.
- After any pairing record exists: listen-only mode; no active scanning/connecting, waiting for paired gamepads to connect themselves.
- Manual
pad_connectalso makes the automatic flow yield (without automatic resumption).Consequently, on a new device, the background flow may restart scanning after the pairing interface finishes scanning but before selection, clearing the engine's result list. Do not connect using the index captured for display; relocate the entry by
addrin the currentpad_found(), or rescan if absent.
pad_scanstate() → number
| Return | Description |
|---|---|
0 | Idle (never scanned / request submitted but not started / unsupported device) |
1 | Scanning |
2 | Complete (retained until the next accepted pad_scan) |
pad_scanstop()
Stops the current scan (effective only while scanning). Results are retained. No return value.
pad_found() → table
Latest scan results, newest first, up to 8 entries. Each contains:
| Field | Type | Description |
|---|---|---|
name | string | Device name; MAC string if no name is reported |
addr | string | Lowercase colon-separated MAC address "xx:xx:xx:xx:xx:xx" |
rssi | number | Signal strength |
The list contains all discovered classic Bluetooth devices, not just gamepads (speakers/headphones included). Automatic connection selects only devices whose names resemble gamepads (wireless controller / dualshock / dualsense / xbox / joy-con / pro controller / 8bitdo / gamepad / joystick, etc.); pairing interfaces let the user choose, so results are not filtered for you.
function _update()
local st = pad_scanstate()
if st == 0 then
pad_scan(8) -- Start scanning
elseif st == 2 then
for i, d in ipairs(pad_found()) do
print(i, d.name, d.addr, d.rssi)
end
end
end
Connecting
pad_connect(idx [, p]) → boolean
Connects scan result idx (0-based) to player p (default 0).
- Returns immediately:
true= connection started in the background; checkpad_conn(p)/pad_status()after a few frames.false= failure (index out of range / stack not started); seepad_lasterr(). - If the player slot already has another gamepad, the old one is displaced first.
- A successful connection automatically adds the gamepad to the persisted pairing list for reconnection at the next boot.
local list = pad_found()
if #list > 0 then
pad_connect(0, 0) -- Connect the first scan result to player 0 (idx is zero-based!)
end
pad_disconnect([p]) → boolean
Disconnects player p (default 0). Also asynchronous: true means initiated;
pad_conn(p) becomes false after a few frames. Returns false if the slot was already empty.
Disconnects without deleting pairing records; a paired gamepad may reconnect after a button press.
To prevent reconnection, use pad_unpair / pad_forget below.
Paired List / Remove / Clear
pad_bonds() → table
Paired gamepads (reconnect at boot), same structure as pad_found(), up to 8 entries
(rssi is always 0 and meaningless here). Stored in a file and retained across restarts.
The startup reconnection policy is listen-only, not active connection: pressing any button on a paired gamepad or having it initiate a connection reconnects it.
pad_unpair(idx) → boolean
Deletes pairing entry idx (0-based).
Deletes the record without disconnecting; a currently connected gamepad remains usable. The effect appears on its next reconnection/boot.
Returns false for an out-of-range index.
pad_forget()
Clears all pairing records. Same semantics: currently connected gamepads remain connected. No return value.
for i, d in ipairs(pad_bonds()) do print(i, d.name) end
pad_unpair(0) -- Delete the first pairing record (zero-based idx)
pad_disconnect(0) -- Disconnect player 0 (keep the pairing record)
pad_forget() -- Clear all pairing records
Current Connection Information
pad_info([p]) → table / nil
Information for the gamepad in player slot p ({name=, addr=, rssi=}, same structure as above);
returns nil if disconnected. rssi is meaningless (always 0); use pad_found() for signal strength.
Diagnostics
pad_status() → string
Current gamepad bus state for interface display:
| Return | Meaning |
|---|---|
"Off" | Bluetooth stack not started |
"Idle" | Idle (neither scanning nor connecting) |
"Scanning" | Scanning |
"Connecting" | Connecting |
"Connected" | At least one gamepad connected |
Returns an empty string "" on unsupported devices.
pad_lasterr() → string
Reason for the last failed management operation (empty string = no failures yet). Successful operations do not clear it; it remembers the most recent failure. Common values:
"扫描请求被拒(可能正在扫描/连接)""连接失败(下标越界,或没起栈)""该槽没有已连接的手柄""删除失败(序号越界)"
if not pad_connect(0) then
print(pad_lasterr()) -- Failure reason
end
6. Complete API Index
| Function | Module | Returns | Description |
|---|---|---|---|
usemod('pad') | — | boolean | Enable gamepad state API |
usemod('padmag') | — | boolean | Enable gamepad management API |
pad_state([p]) | pad | number | Held button bitmask |
pad_btn(id [, p]) | pad | boolean | Whether a button is held |
pad_stick([p]) | pad | number ×4 | lx, ly, rx, ry (0 = centered) |
pad_conn([p]) | pad | boolean | Whether a player slot has a gamepad |
pad_assys([on]) | pad | boolean | Merge gamepad into btn(); read/write, default true |
pad_scan([sec]) | padmag | boolean | Start an asynchronous scan (true = accepted; default 8 seconds) |
pad_scanstop() | padmag | — | Stop scanning (retain results) |
pad_scanstate() | padmag | number | 0=idle, 1=scanning, 2=complete |
pad_found() | padmag | table | Scan results (newest first, up to 8), each {name=, addr=, rssi=} |
pad_connect(idx [, p]) | padmag | boolean | Connect scan result idx (0-based) to player p |
pad_disconnect([p]) | padmag | boolean | Disconnect player p (asynchronous, keep pairing) |
pad_bonds() | padmag | table | Paired list, same structure (up to 8) |
pad_info([p]) | padmag | table / nil | Current player p gamepad information; nil if disconnected |
pad_unpair(idx) | padmag | boolean | Delete paired entry idx (0-based, keep current connection) |
pad_forget() | padmag | — | Clear all pairing records (keep current connections) |
pad_status() | padmag | string | Gamepad bus state (Off/Idle/Scanning/Connecting/Connected) |
pad_lasterr() | padmag | string | Last failure reason (not cleared on success) |
pad_auto() | padmag | boolean | Return control to the automatic unattended scan→select→pair→connect flow; manual pad_connect mode becomes inactive; true = accepted |
PAD Constants
| Constant | |||
|---|---|---|---|
PAD.A | PAD.B | PAD.X | PAD.Y |
PAD.L | PAD.R | PAD.L2 | PAD.R2 |
PAD.L3 | PAD.R3 | PAD.MENU | |
PAD.UP | PAD.DOWN | PAD.LEFT | PAD.RIGHT |
PAD.START | PAD.SELECT |
7. Relationship to btn()
btn()/btnp()are unaffected; onboard buttons work as before.- Gamepads also drive
btn(): player 0's buttons are merged into its stream, allowing a single gamepad to play old cartridges without changes.
Mapping (left = gamepad button, right = coloX button position, not the similarly named gamepad button):
| Gamepad button | coloX button position |
|---|---|
| D-pad Up / Down | X / Y |
| D-pad Left / Right | LEFT / RIGHT |
| Action buttons A / B | A / B |
| Start | CENTER |
| Select / Menu | SYS |
Names map naturally. Note that coloX's 8 button positions have no Up/Down, so D-pad directions borrow
X/Y. Usepad_btn()directly in new cartridges, rather than routing throughbtn(); this table only explains how older cartridges also work with gamepads.
Select and Menu/Home both merge into SYS. Neither opens the system menu inside a cartridge;
the menu reads another channel (the onboard P button), unaffected by gamepad buttons.
The second (player) parameter of btn(id, p) currently supports only 0. Use pad_* for player 1 input.
pad_assys([on]) → boolean
Controls whether the gamepad acts as system buttons, i.e. whether it merges into btn() / btnp().
Without arguments, reads and returns the current value. Default true (the mapping above describes true).
pad_assys(false) -- Stop driving btn() from the gamepad; read pad_* directly
pad_assys(true) -- Restore the default
When disabled:
- Gamepads no longer appear in
btn()/btnp(), including directions and buttons (not a partial direction-only disable); pad_state/pad_btn/pad_stick/pad_connremain available; they simply stop also feedingbtn(). Use this when a cartridge handles its own gamepad input to avoid reading the same device twice;- The system menu is unaffected: gamepads still navigate and open it. Cartridges cannot disable that channel, preventing users from being trapped in a game if a cartridge forgets to restore it.
This is a setting, not a state: it persists across cartridge switches, and the next cartridge inherits your value. Cartridges that do not need this capability should leave it alone; the default matches older cartridges' expectations.