_init
_init() ... end
Runs once when the cartridge starts. Code that sits outside any hook is also folded into _init.
_init()
x = 64
y = 40
endThe language is a small Lua-style script. This half starts from an empty project, teaches the language, and then shows a short example of every function.
Create a project at 64×64, 4-bit color. Open CODE. Replace the tab with:
_init()
x = 20
y = 40
end
_update()
if btn(0) then x -= 1 end
if btn(1) then x += 1 end
if btn(2) then y -= 1 end
if btn(3) then y += 1 end
end
_draw()
cls(1)
print("HI", 4, 4, 7)
circfill(x, y, 4, 8)
end
Ctrl+R runs it. Arrow keys move the circle. Escape stops the game and returns to the editor.
The same three calls: cls(1) paints the navy screen, print draws HI, and circfill draws the pink circle.
_init runs once._update runs at 60 Hz. Put movement and buttons here._draw paints. With no fps argument it paints as fast as the computer and the monitor can go. _draw(30) caps painting at 30 fps and leaves logic at 60._set_fps(n) changes that cap later. 0 clears it.Names are case-insensitive; the editor stores them in lowercase. function and fun are the same keyword.
A program is a list of lines the cartridge runs. Each heading shows the shape of the line first, then a small example. A line that starts with -- is a comment: a note for you. The game skips it.
A variable is a name that holds a value. You pick the name. Later lines can read it, and they can store a new value in the same name.
The shape is name = value. local name = value keeps that name inside the current block, so the rest of the cartridge cannot see it. Without local, the name is global and every tab can see it.
hp = 3 -- global: the whole cart can read and change hp
local coins = 0 -- local: only this block can see coins
hp = hp + 1 -- read 3, add 1, store 4 back into hp
nil means there is no value. true and false are yes and no. A name you have never set reads as nil.
bonus = nil -- nothing stored yet
if bonus == nil then -- condition: is bonus empty?
bonus = 0 -- body: store a number
end
A table holds many values under one name. A list uses numbers. The first item is 1, not 0. A record uses names. A table can hold another table.
List shape: { value, value }. Record shape: { name = value, name = value }. A list of records is a table whose items are tables.
-- a list. [1] is the first item
scores = {10, 20, 30}
print(scores[1], 1, 1, 7) -- print draws text. this draws 10
-- a record. player.x is the field named x
player = {x = 10, y = 20}
print(player.x, 1, 8, 7) -- draws 10
-- a list of records. enemies[1] is the first record
enemies = { {x = 4, y = 8}, {x = 20, y = 12} }
print(enemies[1].x, 1, 16, 7) -- draws 4
print(enemies[2].y, 1, 24, 7) -- draws 12
A condition is a question with a yes or no answer, such as hp > 0 or btnd(4). A body is the group of lines that run when you enter a block. if and every loop use that same shape: a condition, then a body, then end. repeat closes with until instead of end.
if runs its body only when the condition is true. elseif tries another condition. else runs when every condition was false.
Shape: if condition then, then the body, then end.
hp = 2
if hp > 0 then -- condition: is hp above zero?
print("ok", 1, 1, 7) -- body: print draws the word ok
elseif hp == 0 then -- another condition
print("empty", 1, 1, 7)
else
print("no", 1, 1, 7) -- body when every condition was false
end
if hp > 0 print(hp, 1, 32, 7) -- one call, no then/end. draws 2
A loop repeats a body. while checks the condition first and keeps going while it stays true. repeat runs the body, then checks, so the body always runs at least once. for counts. The last number is included. Without a third number the step is 1, so if the start is already past the end the body does not run. Counting down needs a negative step.
n = 0
while n < 3 do -- condition: keep going while n is under 3
n += 1
print(n) -- 1, then 2, then 3: how many times the body has run
end
n = 0
repeat
n += 1
print(n) -- body first, then the condition. prints 1, then 2, then 3
until n > 2
for i = 1, 3 do -- i is 1, then 2, then 3
print(i)
end
for i = 0, 4, 2 do -- start, end, step of 2
print(i) -- 0, then 2, then 4
end
for i = 3, 1, -1 do -- counting down needs the step
print(i) -- 3, then 2, then 1
end
for i = 1, 5 do
if i == 3 then break end -- leave the loop when i reaches 3
print(i) -- 1, then 2
end
all visits each item of a list, from the first. pairs visits each name and the value stored under that name.
t = {1, 2, 3} -- list: t[1] is 1, t[2] is 2, t[3] is 3
for v in all(t) do -- v is 1, then 2, then 3
print(v) -- print draws that number
end
player = {x = 10, y = 20} -- record: a field x and a field y
for k, v in pairs(player) do
print(k) -- k is the name, "x" then "y"
end
A function is a named recipe. The shape is function name(arguments), then a body, then end. You call it by writing the name and parentheses. return sends a value back, and it can send more than one. The arguments are locals of that function.
function greet(who) -- who is a local that holds what you pass in
return "hi "..who -- .. glues two texts. return sends the result back
end
print(greet("ada")) -- draws hi ada
function pair()
return 1, 2 -- two values
end
a, b = pair() -- a becomes 1, b becomes 2
local function is a function that can see the locals around it. That is a closure. A table can hold one, and you call it with a dot.
function make()
local n = 0
local m = {}
m.bump = function() -- this function sees n
n += 1
return n
end
return m
end
counter = make()
print(counter.bump()) -- 1
print(counter.bump()) -- 2
not flips a condition. and is true only when both sides are true. or is true when either side is true. a and b or c picks b when a is true, otherwise c. cond ? a : b is the same idea in one line: a when the condition is true, b when it is not.
hp = 2
hit = false
night = false
if hp > 0 and not hit then -- both parts are true, so the body runs
print("safe", 1, 1, 7) -- draws safe
end
label = hp > 0 and "ok" or "out" -- hp is above 0, so label is ok
print(label, 1, 8, 7)
shade = night ? 1 : 7 -- night is false, so shade is 7
print(shade, 1, 16, 7)
+ - * / are add, subtract, multiply, and divide. // divides and keeps the whole number. % is the remainder. ^ is power. .. glues two texts. #t is how many items are in a list. Comparisons are == (same), ~= or != (different), and < > <= >=. x += 1 adds 1 to x. The same shape works for -= *= /= ^= %=.
scores = {10, 20, 30} -- the list named scores
tiles = 15 // 8 -- 1, the fraction is dropped
left = 15 % 8 -- 7, what is left over
title = "hi ".."ada" -- the text hi ada
n = #scores -- how many items are in the list named scores
print(n, 1, 1, 7) -- 3
print(title, 1, 8, 7)
score = 0
best = 10
if score ~= best then -- condition: score is not the best
score += 10 -- add 10 to score
end
print(score, 1, 16, 7) -- 10
local lasts until the end that closes its block. if / end is its own block. You may mention a local above the line that sets it, but until that line runs the value is nil.
if true then
print(coins) -- nil: the next line has not run yet
local coins = 5
print(coins) -- 5
end
-- coins does not exist out here
::label:: marks a line. goto label jumps there, but only inside the same function.
x = 0
::again::
x += 1 -- add 1
if x < 3 then goto again end -- condition: jump back while x is under 3
peek and poke look at live pixels through one 16-bit address. They do not keep a second copy of the cartridge. Addresses 0x5F00 through 0x5FFF are registers: camera, clip (read only), draw color, fill pattern, the three palette remaps, and the page numbers. The bytes on both sides of that hole, 65280 of them, are the pixel window.
When the screen fits in those 65280 bytes, 64×64 and 128×128 do and 256×256 does not, the screen starts at address 0, row by row. What is left is the sprite sheet selected by 0x5F41 (0 is sheet 0). If that sheet is bigger than the space left, 0x5F42 picks the page and the map is not in the window. If the sheet fits, the tail is map cells from the map selected by 0x5F43, one or two bytes each, and 0x5F44 pages the map when it does not fit in the tail.
When the screen does not fit, the whole window is one page of 65280 pixels. poke(0x5F40, n) turns the screen page. poke(0x5F41, n) with n other than 0 shows sheet n instead, and sheet 0 has no view in this mode. poke(0x5F43, n) with n other than 0 shows map n, and that wins over the sheet. Map 0 in this mode is only mget and mset.
A peek that does not land on a pixel or a register returns 0. A poke there does nothing. Sprite flags, SFX, and DATA tables are not in this window. Use fget, sfxget, and dget.
Every function is listed at the bottom of this page, with practical uses of PIX37 functions. The links under each example open more about the functions.
A 128×128 cart, seen from above. Sprite 1 is already drawn. Arrows accelerate in any direction, and friction slows you down. The sprite wraps: a half that leaves the bottom is drawn at the top, and the same for the other edges.
_init _update _draw btn mid cls spr palt
A 64×64 cart. The floor and the right-hand wall are already on the map, painted with sprite 3, and flag 0 is set on that sprite. Arrows move sprite 1. The word at the top says blocked when the next step would overlap a solid tile, and free when it would not.
flr fget mget btn cls map spr print _update _draw
Press A. The wipe is drawn by flip(), one black row at a time, instead of inside _draw(). _draw stays out of the way while that runs, so each row stays on screen.
rectfill flip btnd cls print _update _draw
Sprite 1 is already drawn. make_monster works like a class. It returns a table, and update and draw are methods that keep that monster's own x and y. The number at the top is how far it has walked.
spr cls print flr _init _update _draw
A is button 4. Hold it and charge climbs. Release it and charge goes back to 0. Up and down repeat while held, so the menu row keeps moving. btnd is the first frame of a press, which this cart uses only as the start of that hold.
btn btnd btnp btnu cls print _update _draw
Sprite 1 is already drawn in the middle. A white dot is the cursor. Left click fires a pixel toward it. The wheel changes the speed, printed in the corner.
scroll clickl mouse sqrt add all cls spr pset print _update _draw
Press A to open the field. Up and down change a blinking letter. A writes it, X deletes, Y is space, and B confirms. The line then says your name.
btnd keyon keystr flr time cls print _update _draw
A 128×128 cart. Sprite 1 starts in the middle of a floor of tiles. Arrows move. The camera keeps the sprite centered. x and y in the corner do not scroll, because camera() with no arguments puts the view back for the HUD.
btn screen camera cls map spr print flr _update _draw
The lines are in DATA, in English and Polish. A continues, or picks stay when a choice is on screen. B picks leave on a choice, and otherwise swaps the language. X swaps the language while a choice is showing. The dialogue uses the 8px font so Polish letters draw.
dstr dget btnd cls print8 print _update _draw
A 64×64 cart, so address 0 is the top-left pixel and the next row starts at 64. The cart writes pixels, copies a row, clears a row, and prints the values it read back.
cls poke peek poke2 peek2 poke4 peek4 memcpy memset print _draw
A adds a number, up to 8. B removes the last. X removes the first. The list is printed down the screen.
btnd count add deli cls ipairs print pack unpack next foreach select pcall assert del _update _draw
The cart splits ada,12,blue and prints the name, its first letter, 12, and the word blue.
cls split sub chr ord tonum tostr print _draw
Pattern 0 is one note long, and every replay is the same loudness. A plays it again when that note has finished. B raises the pitch and plays that note.
sfxset sfxhdr sfx btnd sfxstat sfxget cls print _init _update _draw
Two patterns loop on row 0, one on each of the first two channels. row stays 0. ch0 and ch1 are the note each channel is on. Editing the pattern, LEN, and LOOP in the cart is a way to see what those controls do in the music panel.
songget songset music musicstat cls print _init _draw
The DATA panel already has a name column and an hp column, with slime, bat, and eye. A hurts the slime. The numbers on the right are its hp.
drows dstr dget add btnd dset dcols cls print all _init _update _draw
A adds a point and saves it. Quit and open the cart again: the number is still there. B forgets it.
load btnd save delsave cls print _init _update _draw
Two carts share the save slot quest. Part 1: A marks the game finished. Part 2, opened first, says to finish part 1. After that, part 2 opens, and B erases the save so part 1 can be played again.
load saveslot btnd save delsave cls print _init _update _draw
Sprite 8 is already drawn. Press A ten times. The toast names the achievement, and sprite 8 stays because it is unlocked. B clears that achievement in the local file and resets the count.
achdef btnd achieved achieve achclear cls print spr _init _update _draw
A 256×256 cart. A white dot is the cursor. The menu is host, join, or the server list. Host opens a room named walk and starts the game. Join scrolls an address (digits, a dot, a colon) and B connects. The server list moves with up and down, and A joins the row. In the game, arrows walk sprite 1. One coin is shared: the host moves it, and picking it up adds 1 to that player's score and spawns the next. Every sprite, including yours, shows that score beside it. The corner shows how many players are in, the LAN address, and the host's public address. B leaves: you and the others return to the menu, and the next host starts a new room at score 0.
btn btnd mouse pset spr print flr rnd pairs nlisten nhost nannounce nlist njoin nleave nsend nkb nkbstr whoami nplayers nlan _mp _mp_join _mp_leave _mp_fail palt cls time _init _update _draw
A shows the next line. The function pauses at each yield until you press A again.
yield cocreate btnd coresume cls print _init _update _draw
The word changes from ... to hi after about half a second. The screen keeps drawing while the coroutine is paused.
yield cocreate costatus coresume cls print _init _update _draw
Five circles drip in from the top, two frames apart, and then fall.
add yield cocreate coresume all cls circfill _init _update _draw
Sprite 1 and sprite 2 are two frames of the same character. The picture swaps four times a second.
Arguments in square brackets are optional. Indexes of tables and strings start at 1, except DATA rows and columns, which start at 0. Colors are palette indexes.
_init_init() ... end
Runs once when the cartridge starts. Code that sits outside any hook is also folded into _init.
_init()
x = 64
y = 40
end_update_update() ... end
Game logic. Called at 60 Hz, even when _draw is capped or the host is slower. Read buttons here.
_update()
if btn(0) then x -= 1 end
if btn(1) then x += 1 end
end_draw_draw([fps]) ... end
Draws one frame. With no argument, or 0, it runs as often as the host presents. Pass n (1..999) to cap drawing at n frames per second. _update stays at 60 Hz.
_draw(30)
cls(1)
spr(1, x, y)
end_set_fps_set_fps(n)
Changes the _draw cap while the game is running. 0 means uncapped. n is clamped to 0..999.
if btn(4) then _set_fps(60) endflipflip()
Presents the screen and yields until the next frame. Use it only if you are drawing your own frame loop. Do not busy-wait after it.
cls(0)
print("tick", 4, 4, 7)
flip()timetime()
Seconds since _init.
print(time(), 4, 4, 7)btnbtn([b], [p])
1 while button b is held, otherwise 0. p is the player, 0..7. With no arguments it returns a bit mask of player 0. Buttons: 0 left, 1 right, 2 up, 3 down, 4 A, 5 B, 6 X, 7 Y, 8 R, 9 L, 10 select, 11 start.
if btn(4) then shoot() endbtndbtnd(b, [p])
True only on the _update frame when button b goes down.
if btnd(5) then menu_open = not menu_open endbtnpbtnp([b], [p])
True on press, then again while held: 30 ticks of delay, then every 8 ticks. With no button it returns a mask.
if btnp(2) then cursor -= 1 endbtnubtnu(b, [p])
True only on the frame the button is released.
if btnu(4) then charge = 0 endmousemouse()
Returns mouse x, y in game pixels.
mx, my = mouse()
pset(mx, my, 7)clicklclickl([p])
Left mouse button. clickl() is held. clickl(1) is the press edge.
if clickl(1) then place(mouse()) endclickrclickr([p])
Right mouse button. Same 1-argument edge as clickl.
if clickr() then cancel() endclickmclickm([p])
Middle button, or a click of the scroll wheel.
if clickm(1) then drag = true endscrollscroll()
Mouse-wheel movement this frame. Positive and negative depend on the wheel direction.
cam_y -= scroll()keyonkeyon()
Opens a text field driven by buttons. Up and down change a letter A–Z. A writes that letter. X deletes. Y is space. B confirms and closes the field. The keyboard does not type into it.
if btnd(4) then keyon() endkeyoffkeyoff()
Hides the text field.
keyoff()keystrkeystr([s])
Text in the field, then 1 on the frame B confirms, then the letter up and down are changing. That letter is empty once the field closes. keystr("") clears the text.
name, done, letter = keystr()
if done == 1 then start(name) endkeystatkeystat()
1 while the text field is open, otherwise 0.
if keystat() == 1 then return endscreenscreen()
Current cartridge screen size in pixels. Returns width, then height. This is the game resolution, not the editor window.
w, h = screen()clscls([col])
Clears the screen. Default color is 0.
cls(1)colorcolor(col)
Sets the draw color used when a later call omits col. With no argument it returns the current color.
color(7)
print("hi")cameracamera([x, y])
Offsets every draw call. camera() resets to 0, 0.
camera(cam_x, cam_y)clipclip([x, y, w, h, clip])
Limits drawing to a rectangle. A nonzero fifth argument intersects with the current clip. clip() restores the full screen. Peek of the clip registers is read-only.
clip(8, 8, 48, 48)
circfill(32, 32, 20, 8)
clip()cursorcursor([x, y, col])
Sets where the next print without coordinates goes, and optionally the color. cursor() returns x, y.
cursor(4, 4, 7)
print("line 1")
print("line 2")psetpset(x, y, [col])
Sets one screen pixel. Counts toward the px stat.
pset(x, y, 10)pgetpget(x, y)
Color of the screen pixel at x, y.
if pget(x, y+8) == 3 then grounded = true endprintprint(v, [x, y, col])
Draws 3×5 text (UTF-8, cropped from the Fusion font). Without x, y it prints at the cursor and moves to the next line.
print("score "..score, 2, 2, 7)loglog(...)
Appends the arguments, separated by spaces, to a text buffer. pix37_run prints that buffer on stdout. It does not draw.
log("hp", hp)print8print8(v, [x, y, col])
Same as print, with the 8 px Fusion font.
print8("pause", 16, 28, 7)print10print10(v, [x, y, col])
Same as print, with the 10 px Fusion font.
print10("pix37", 8, 8, 10)lineline([x0, y0, x1, y1, col])
Line from x0,y0 to x1,y1. Two arguments continue from the previous end. line() resets that chain.
line(0, 32, 63, 32, 6)circcirc(x, y, r, [col])
Circle outline. Radius is in pixels.
circ(32, 32, 12, 12)circfillcircfill(x, y, r, [col])
Filled circle.
circfill(x, y, 3, 8)ovaloval(x0, y0, x1, y1, [col])
Ellipse outline inside the bounding box. Corners are inclusive.
oval(8, 20, 56, 44, 7)ovalfillovalfill(x0, y0, x1, y1, [col])
Filled ellipse in a bounding box.
ovalfill(10, 40, 54, 60, 3)rectrect(x0, y0, x1, y1, [col])
Rectangle outline. Corners are inclusive.
rect(0, 0, 63, 63, 7)rectfillrectfill(x0, y0, x1, y1, [col])
Filled rectangle.
rectfill(0, 56, 63, 63, 3)rrectrrect(x, y, w, h, [r, col])
Rounded rectangle outline. x, y is the top left. w and h are the size in pixels; both must be greater than 0. r is the corner radius and defaults to 0. It is clamped to half of the shorter side.
rrect(8, 8, 48, 16, 3, 7)rrectfillrrectfill(x, y, w, h, [r, col])
Filled rounded rectangle. Same arguments as rrect.
rrectfill(8, 40, 48, 16, 2, 1)fillpfillp([p])
16-bit fill pattern for later filled shapes. 0 is solid. fillp() returns the current pattern. Bits walk the 4×4 pattern.
fillp(0xA5A5)
rectfill(8, 8, 40, 40, 10)
fillp(0)palpal([c0, c1, [mode]])
Remaps color c0 to c1. mode 0 is the draw palette, 1 the display palette, 2 the fill-pattern palette. pal() resets.
pal(8, 10)
circfill(32, 32, 8)palrgbpalrgb(col, r, g, b)
Sets one palette entry to RGB, each channel 0..255.
palrgb(8, 255, 80, 40)paltpalt([col, t])
Transparency. palt(col) or palt(col, true) makes col transparent. palt(col, false) makes it solid. palt() makes every color opaque.
palt(0)
spr(1, x, y)setpalettesetpalette(n)
Selects palette bank n. setpalette() returns the current bank.
setpalette(1)tlinetline(x0, y0, x1, y1, mx, my, [mdx, mdy])
Draws a line on the screen while sampling map pixels from map position mx, my. mdx, mdy step the map sample along the line.
tline(0, 40, 63, 20, 0, 0, 0.5, 0)sprspr(n, x, y, [w, h, fx, fy, tex, rot])
Draws sprite n at x, y. w and h are the size in pixels, default 8. fx and fy flip horizontally and vertically when nonzero. tex is the sprite-sheet tab. rot is the angle in turns (0..1), same direction as sin and cos. 0 leaves the sprite unrotated.
spr(1, x, y, 8, 8, 0, 0, 0, aim)ssprsspr(sx, sy, sw, sh, dx, dy, [dw, dh, fx, fy, tex])
Copies a rectangle of the sprite sheet to the screen, scaled to dw by dh. Defaults keep the source size.
sspr(0, 0, 8, 8, 16, 16, 32, 32)sgetsget(x, y, [tex])
Color of one texel on the sprite sheet.
c = sget(0, 0)ssetsset(x, y, [col, tex])
Writes one texel on the sprite sheet.
sset(3, 3, 8)fgetfget(n, [f, tex])
Sprite flags. fget(n) returns the flag byte. fget(n, f) is true when flag bit f (0..7) is set.
if fget(tile, 0) then solid = true endfsetfset(n, [f], v, [tex])
Sets sprite flags. fset(n, v) writes the whole byte. fset(n, f, v) sets one bit.
fset(2, 0, true)setsprsetspr(n)
Selects the active sprite sheet. setspr() returns the current sheet. Same bank as settex.
setspr(1)settexsettex(n)
Alias of setspr.
settex(0)mapmap(cx, cy, sx, sy, [cw, ch, layer, tex])
Draws the map. Cell cx, cy of the map is drawn at screen sx, sy. cw, ch of 0 means the whole map. layer is accepted and ignored. tex is the tileset sheet.
map(0, 0, 0, 0, 16, 16)mgetmget(cx, cy)
Sprite id in map cell cx, cy.
if fget(mget(tx, ty), 0) then bounce() endmsetmset(cx, cy, n)
Writes sprite n into map cell cx, cy.
mset(3, 4, 0)setmapsetmap(n)
Selects map n. setmap() returns the current map. Map 0 is a real map.
setmap(1)peekpeek(addr)
Reads one byte of the 64 KB window. The window is the live screen, then sprite pixels, then map cells when the screen fits in 65280 bytes. Larger screens are paged with poke(0x5F40, page). Addresses that are not mapped return 0. Also written @addr.
px = peek(0)pokepoke(addr, ...)
Writes bytes at addr. Extra arguments write the following bytes. Unmapped addresses are ignored. Also written $addr, val. Poking the screen counts as a pixel write.
poke(0x5F00, 4) -- camera xpeek2peek2(addr)
Unsigned 16-bit value, little-endian, at addr.
w = peek2(0x6000)poke2poke2(addr, val)
Writes an unsigned 16-bit value, little-endian.
poke2(0x6000, 1000)peek4peek4(addr)
Unsigned 32-bit value, little-endian.
n = peek4(0x6000)poke4poke4(addr, val)
Writes an unsigned 32-bit value, little-endian.
poke4(0x6000, 1)memcpymemcpy(dst, src, len)
Copies len bytes inside the same 64 KB window.
memcpy(0x6000, 0x6100, 64)memsetmemset(dest, val, len)
Fills len bytes starting at dest with val.
memset(0, 0, 64)absabs(x)
Absolute value.
d = abs(tx - x)flrflr(x)
Rounds toward minus infinity.
tx = flr(x / 8)ceilceil(x)
Rounds toward plus infinity.
n = ceil(hp / 8)maxmax(a, b)
Larger of the two values.
x = max(0, x)minmin(a, b)
Smaller of the two values.
x = min(63, x)midmid(a, b, c)
Middle of the three values. Useful as a clamp.
x = mid(0, x, 63)sgnsgn(x)
Sign of x: -1, 0, or 1.
x += sgn(dir)sqrtsqrt(x)
Square root. A negative argument is not a number.
dist = sqrt(dx*dx + dy*dy)sinsin(x)
Sine. x is in turns: 0, 0.25, 0.5, 0.75 go around the circle once. Not radians.
y = 32 + sin(time()) * 8coscos(x)
Cosine, in turns, same convention as sin.
x = 32 + cos(time()) * 8atan2atan2(dx, dy)
Angle of the vector dx, dy, in turns from 0 to 1.
aim = atan2(mx - x, my - y)rndrnd([x])
Random number in [0, x). Default x is 1, so rnd() is 0..1. For a die, flr(rnd(6))+1.
c = flr(rnd(16))srandsrand(seed)
Seeds the random generator so a later rnd sequence can be repeated.
srand(1)bandband(a, b)
Bitwise AND. Also written a & b.
if band(flags, 1) ~= 0 then hit() endborbor(a, b)
Bitwise OR. Also written a | b.
flags = bor(flags, 4)bxorbxor(a, b)
Bitwise XOR. Also written a ^^ b.
n = bxor(n, 255)bnotbnot(a)
Bitwise NOT. Also written ~a.
mask = bnot(1)shlshl(a, n)
Shift left. Also written a << n.
n = shl(1, bit)shrshr(a, n)
Arithmetic shift right. Also written a >> n.
n = shr(n, 1)lshrlshr(a, n)
Logical shift right. Also written a >>> n.
n = lshr(n, 4)rotlrotl(a, n)
Rotate bits left. Also written a <<> n.
n = rotl(n, 1)rotrrotr(a, n)
Rotate bits right. Also written a >>< n.
n = rotr(n, 1)addadd(t, v, [i])
Appends v to table t. If i is given, inserts at that 1-based index.
add(bullets, {x=x, y=y})deldel(t, v)
Removes the first entry equal to v.
del(items, gem)delideli(t, [i])
Removes index i and returns that value. With no i, removes the last entry.
local b = deli(bullets, i)allall(t)
Iterator over the array part, in order. Holes stop the walk the way a 1-based array ends.
for b in all(bullets) do
b.x += 2
endforeachforeach(t, fn)
Calls fn(v) for each array element.
foreach(enemies, draw_enemy)pairspairs(t)
Iterator over every key and value, including named fields.
for k, v in pairs(player) do
print(k)
endipairsipairs(t)
Iterator over the array part with the 1-based index.
for i, v in ipairs(deck) do
spr(v, i*8, 8)
endnextnext(t, [k])
Returns the next key and value after k. next(t) starts at the beginning. Used by pairs.
k, v = next(t)countcount(t, [v])
Length of the array part. If v is given, counts how many entries equal v.
if count(gems) == 0 then win() endpackpack(...)
Packs the arguments into a new table.
t = pack(1, 2, 3)unpackunpack(t, [i, j])
Returns t[i] through t[j] as separate values. Defaults cover the whole array part.
a, b = unpack(t)selectselect(i, ...)
select("#", ...) returns how many arguments follow. select(i, ...) returns the arguments from i onward.
n = select("#", 1, 2, 3)assertassert(c, [msg])
Stops with an error when c is false or nil. msg replaces the default text.
assert(hp > 0, "dead")pcallpcall(f, ...)
Calls f. On success returns true and the results. On error returns false and the error text.
ok, err = pcall(load_level, 3)chrchr(n)
One character from a byte code 0..255.
s = chr(65) -- Aordord(s, [i, j])
Byte codes of s from index i to j. Indexes are 1-based. Defaults to the first character.
code = ord("a")subsub(s, i, [j])
Substring from i to j, 1-based. Omit j to take the tail.
name = sub(keystr(), 1, 8)splitsplit(s, [sep, conv])
Splits s into a table. sep defaults to comma. A number sep is a chunk width. conv converts pieces with tonum when it is true.
words = split("red,blue", ",")tonumtonum(s, [base])
Parses a number. base may be 2..36. Returns nil when the text is not a number.
n = tonum("255")tostrtostr(v, [digits])
Turns a value into text. digits sets decimal places for numbers.
print(tostr(hp, 0), 4, 4, 7)sfxsfx(n, [ch, offset, len])
Plays pattern n and returns the channel. Omit ch, or pass -1, and the first free channel is chosen. ch -2 stops pattern n on every channel. n -1 stops a channel, or every channel when ch is omitted. n -2 lets a looping pattern finish instead of looping. sfx() with no arguments returns -1.
ch = sfx(0)sfxgetsfxget(n, step)
Returns a table of one pattern step: [1] pitch, [2] wave, [3] volume, [4] effect. Pitch is 0..63 (C-0 through D#5). Wave is 0..15. Volume is 0..7, and 0 is silent. Effect is 0..7.
step = sfxget(0, 0)
pitch = step[1]sfxsetsfxset(n, step, pitch, wave, vol, fx)
Writes one pattern step. All six arguments are required.
sfxset(0, 0, 24, 3, 5, 0)sfxhdrsfxhdr(n, [key, val])
Pattern header. sfxhdr(n) returns the header table. sfxhdr(n, key, val) sets one field: speed, loop_in, loop_out, level, noise, crush, dtune, rverb, dampn, swing, steps. Numbers 0..10 select the same fields in that order. speed is TIC, ticks per step. Higher is slower. 15 is 120 beats per minute. 16-bit accepts 1..255. Narrower synths snap to their TIC list.
sfxhdr(0, "speed", 15)sfxstatsfxstat([ch])
Pattern id playing on channel ch, or -1. Default channel is 0.
if sfxstat(0) < 0 then sfx(1) endnotenote(pitch, [wave, vol, fx, ch, ticks])
Plays one note without a pattern. pitch 0..63, wave 0..15, volume 0..7, effect 0..7. ticks is how long it holds, in the same 120 Hz ticks as TIC. Omit ticks and it lasts 15, one default step. The effect runs across that time, then the channel goes quiet.
note(36, 3, 5, 5, 0)musicmusic([n, fade, mask])
Starts song n from the top. music(-1) stops. Calling music with the id that is already playing leaves it running. music() returns the playing song id, or -1. fade is milliseconds: the song fades in, or fades out when n is -1. mask bits that are set are the channels used for the song. 0 means all eight. The other channels stay free for sfx.
music(0, 1000, 7)musicstatmusicstat()
Table of the playing song. song and row are the song id and the row, or -1 when nothing is playing. step and pos have eight numbers. step[1] is channel 0, step[8] is channel 7. step is the note index, or -1 when that channel is silent. pos is how far that note has gone, from 0 to 1. tick is how many ticks this row has already played. played is how many rows have started since music(), including the one that is playing.
st = musicstat()
row = st.row
note = st.step[1]songgetsongget(song, [row, ch])
Pattern id stored in a song cell. ch is 0..7. 255 means the cell is empty. This is the live call; the code hint text still shows an older argument order.
id = songget(0, 0, 0)songsetsongset(song, row, ch, pattern)
Writes a pattern id into a song cell. Use 255 to clear the cell.
songset(0, 0, 0, 1)statstat(n)
Audio only. 16..23 is the sfx id on channel n-16. 24..31 is the music pattern on channel n-24. Any other n returns 0. Frame timing and RAM are perf and info, not stat.
id = stat(16)dgetdget(t, row, col)
Reads a cell of data table t from the DATA panel. row and col start at 0.
hp = dget(0, 0, 1)dsetdset(t, row, col, v)
Writes a cell. Use a string for a text column.
dset(0, 0, 0, "slime")dstrdstr(t, row, col)
The cell as text. Numbers are converted.
name = dstr(0, row, 0)drowsdrows(t)
How many rows table t has.
for r = 0, drows(0) - 1 do
enddcolsdcols(t)
How many columns table t has.
cols = dcols(0)savesave(k, v)
Stores v under key k in the save file. v may be a number, a string, or a table of those. The file is compressed.
save("hp", hp)loadload(k)
Reads key k. Returns nil when the key is missing.
hp = load("hp") or 3delsavedelsave(k)
Deletes key k from the save.
delsave("hp")saveslotsaveslot([name])
Chooses the save file inside the author's folder. With no name, the slot is the game title. Returns 1 when that file already exists.
if saveslot("slot1") == 1 then
hp = load("hp") or 3
endachieveachieve(i)
Unlocks achievement i, from 0 to 15. Stored locally. A Steam build also sets ACH_i. A catalog session reports it to the player's account.
if coins >= 100 then achieve(0) endachievedachieved(i)
1 when achievement i is already unlocked.
if achieved(0) == 1 then spr(8, 4, 4) endachdefachdef(i, text, [spr, tex])
Toast text for achievement i, shown for 15 seconds from the bottom of the screen. spr is an optional 8×8 tile, tex its sheet.
achdef(0, "rich", 8)achclearachclear(i)
Clears achievement i in the local file. A Steam ACH_i that was already set stays set.
if btnd(5) then achclear(0) endwhoamiwhoami()
Your player id, 0..15, while a session is up. Offline it is -1.
id = whoami()nhostnhost()
1 if this machine is the host, otherwise 0.
if nhost() == 1 then spawn() endnplayersnplayers()
How many live ids exist in 0..15.
print(nplayers(), 4, 4, 7)nlistennlisten()
Starts hosting UDP and returns the LAN address as ip:port.
addr = nlisten()njoinnjoin(addr)
Joins ip or ip:port.
njoin("10.0.0.8:7777")nleavenleave()
Leaves the session. Peers see _mp_leave with why 0.
if btnd(11) then nleave() endnsendnsend([p,] name, ...)
Sends a lossy message. Name is the event. Up to four extra values follow. p from 0 to 15 whispers to that peer; omit p to send to everyone.
nsend("pos", x, y)ncallncall([p,] name, ...)
Same shape as nsend, but the message is retried until acknowledged. Three failures in a row kill the session.
ncall("hit", target, dmg)nlannlan()
Current LAN ip:port after nlisten.
print(nlan(), 2, 2, 7)nstunnstun()
Your public ip:port from STUN. A guest on another network can try to join it.
pub = nstun()setturnsetturn(addr, [user, pass])
TURN fallback when a direct path fails. setturn() with empty arguments turns it off. The address is host:port.
setturn("turn.example:3478", user, pass)nlistnlist(game)
Table of open sessions for that game name. Each entry has addr, players, and name.
rooms = nlist("duel")nannouncenannounce(game)
Heartbeat so this host shows up in nlist for game. Call it on a timer while hosting.
nannounce("duel")nkbnkb([on])
Address field. nkb(1) opens it, nkb(0) hides it, nkb() tells you if it is open. Up and down change a character, 0–9 or a dot or a colon. A writes it. X deletes. The keyboard does not type into it.
nkb(1)nkbstrnkbstr([s])
Text in the address field, then the character up and down are changing. nkbstr("") clears the text.
addr, digit = nkbstr()_mp_mp(from, name, ...)
You write this function. It runs when a message arrives. from is the sender id. name is the event. Up to four values follow.
function _mp(from, name, a, b)
if name == "pos" then
px[from] = a
py[from] = b
end
end_mp_join_mp_join(p)
You write this function. A peer received id p. It also fires for you; whoami() is that id.
function _mp_join(p)
add(log, p)
end_mp_leave_mp_leave(p, why)
You write this function. Peer p left. why 0 is a normal leave. why 1 is a lost connection.
function _mp_leave(p, why)
px[p] = nil
end_mp_update_mp_update()
You write this function. It runs every 15 _update frames, about 4 Hz. A good place to nsend positions.
function _mp_update()
nsend("pos", x, y)
end_mp_fail_mp_fail()
You write this function. The session is dead: the host disappeared, or ncall failed three times.
function _mp_fail()
online = false
endcocreatecocreate(f)
Makes a coroutine from function f. It does not run until coresume.
co = cocreate(cutscene)coresumecoresume(c, ...)
Runs coroutine c until it yields or returns. On success: true and the yielded values. On error: false and the error.
ok, a = coresume(co)costatuscostatus(c)
"suspended", "running", or "dead".
if costatus(co) == "dead" then co = nil endyieldyield(...)
Gives control back to whoever called coresume. The values become the results of that coresume.
yield(1)infoinfo([x, y, col])
Draws the live HUD in _draw: fps (1 second average), upd, drw, px, max, ram, peak, ramc, and net when a session is up. info() uses the print cursor. info(col) sets only the color. info(x, y) or info(x, y, col) places it. Numbers use B, k, or m so they fit a small screen. The call itself is not counted in px.
info(1, 1, 7)showstatsshowstats([on])
Same HUD as info, drawn automatically at 0, 0 after _draw, ignoring camera and clip. showstats(0) hides it. showstats(1) or showstats() shows it.
showstats(1)perfperf(n)
One HUD number, so you can draw it yourself. 0 fps, 1 upd, 2 drw, 3 px, 4 max (heaviest frame this second), 5 ram, 6 ramc (ram plus the packed cartridge), 7 peak ram since the cart started.
print(perf(0), 2, 2, 7)