Create: Computing AgesBrass Docs
Reference

Cheat sheet

Brass on one page: the syntax, every library function in one line, the common idioms, the events and the keys. Made to be printed.

Everything at a glance, with a link to the full page of each function. Print it (Ctrl+P) and keep it next to the keyboard.

Syntax

Brass
-- a comment to the end of the line
--[[ a comment on
     several lines ]]
local count = 0                   -- a local variable (use local almost always)
speed = 128                       -- a global variable, seen by every file
local name, open = "Mine", true   -- several at once
local nothing = nil               -- nil: no value; only nil and false are false

-- numbers: 12  3.5  1e3  0xFF     text: "a"  'b'  [[on several lines]]
local x = 7 // 2 + 7 % 2 + 2 ^ 3  -- 3 + 1 + 8: floor division, remainder, power
local line = "Stock: " .. count   -- .. joins text (and numbers)
local size = #line                -- # is the length of a text or a list
-- compare: == ~= (or !=) < > <= >=      logic: and or not

if count > 10 then
  print("many")
elseif count > 0 then
  print("some")
else
  print("none")
end

while count < 3 do count = count + 1 end
repeat count = count - 1 until count == 0
for i = 1, 10 do end                      -- 1, 2 ... 10
for i = 10, 1, -2 do end                  -- 10, 8 ... 2
for i, v in ipairs({"a", "b"}) do end     -- a list, in order
for k, v in pairs({x = 1, y = 2}) do end  -- every key of a table
for v in {"a", "b"} do end                -- the values of a list
-- break leaves the loop

local function area(w, h)
  return w * h                    -- a function returns one value
end
local function corner(w, h)
  return {x = w, y = h}           -- several values: return a table
end

local ores = {"iron", "gold"}             -- a list: ores[1] is "iron"
local stack = {name = "iron", count = 64} -- a record: stack.name, stack["count"]
ores[#ores + 1] = "copper"                -- add at the end
stack.count = nil                         -- remove a key

local loud = ("hello"):upper()   -- string functions work as methods
local r = pcall(area, 2, 3)      -- r.ok, then r.value or r.error

Brass is not Lua (Brass for Lua and ComputerCraft users): a function inside a function cannot use the local variables of the outer one (the file's locals are fine); return a, b does not exist (return a table); no ..., no metatables, no goto; string.find searches plain text, without patterns; pcall returns a table; text is never turned into a number by itself ("10" + 1 is an error).

Libraries

Functions marked ⏸ wait: the program sleeps until they return. Coordinates and positions start at 1.

Base functions

Global functions · every computer

FunctionWhat it does
print(...)prints the values, separated by tabs, then goes to a new line
write(...)prints without going to a new line
read([mask])⏸ waits for a line typed on the keyboard; mask hides it ("*")
sleep(seconds)⏸ pauses the program (by steps of 1/20 s)
tostring(value)any value as text
tonumber(text [, base])text as a number, or nil
type(value)"nil", "number", "string", "boolean", "table" or "function"
pairs(t), ipairs(t)loop over every key, or over t[1], t[2]... until nil
error(message)stops with an error
pcall(f, ...)calls f and catches its errors: {ok = true, value = ...} or {ok = false, error = "..."}
assert(value [, message])an error if value is false or nil, else returns it
import(path), require(path)runs another file once and returns what it returns

math

math · every computer

FunctionWhat it does
math.floor(x), math.ceil(x), math.round(x)rounds down, up, to the nearest
math.abs(x)without its sign
math.min(...), math.max(...)the smallest, the largest
math.sqrt(x), math.exp(x), math.log(x [, base])square root, e to the power x, logarithm
math.sin(x), math.cos(x), math.tan(x)trigonometry, in radians
math.atan(y [, x]), math.atan2(y, x)angle in radians, atan2 knows the quarter
math.fmod(a, b)remainder with the sign of a (% takes the sign of b)
math.random([m [, n]])random: from 0 to 1, from 1 to m, from m to n
math.randomseed(seed)restarts the random sequence
math.pi, math.huge3.14159..., infinity

string

string · every computer · also as methods: s:upper()

FunctionWhat it does
string.len(s)length (like #s)
string.sub(s, i [, j])characters i to j; negative counts from the end
string.upper(s), string.lower(s)capitals, lower case
string.rep(s, n [, sep])repeated n times
string.reverse(s)backwards
string.byte(s [, i]), string.char(...)character code, and back
string.find(s, text [, init])position of text, or nil (plain search)
string.format(fmt, ...)%d %i %f %.2f %s %x %X %% with width: "%5.1f"
string.split(s [, sep])cuts into a list (at spaces by default)
string.trim(s)without the spaces at both ends
string.starts(s, prefix), string.ends(s, suffix)true or false

table

table · every computer

FunctionWhat it does
table.insert(t, [pos,] value)adds at the end, or at pos
table.remove(t [, pos])removes and returns the last value, or the one at pos
table.concat(t [, sep [, i [, j]]])joins the values into one text
table.sort(t [, less])sorts the list in place; less(a, b) says if a comes first
table.copy(t)a shallow copy
table.contains(t, value)true if the value is in the table
table.keys(t)the list of the keys

os

os · every computer

FunctionWhat it does
os.time(), os.clock()ticks, seconds since the computer started
os.day_time()time of the world's day, 0 to 23999 (6000 is noon)
os.id(), os.label([name])number of the computer; its name, read or changed
os.pull_event([name])⏸ the next event (only that name: the others are thrown away)
os.queue_event(name [, data])adds an event to the computer's own queue
os.start_timer(seconds)returns an id; a timer event with that id follows
os.reboot(), os.shutdown()restarts, switches off
os.tier(), os.memory()processor tier (1 to 5); {used = , total = } in cells

term

term · every computer

FunctionWhat it does
term.clear(), term.clear_line()clears the screen, the cursor's line
term.set_cursor(x, y)moves the cursor (1, 1 is the top left)
term.get_cursor(), term.get_size(){x = , y = }, {w = , h = }
term.write(text)writes at the cursor, without new line nor wrapping
term.scroll(n)moves the text up n lines
term.set_fg(color), term.set_bg(color)text and background colour, 0 to 15
term.colorsterm.colors.red... the 16 colours (Colours)

gfx

gfx · every computer but the Tube Computer · colours: 0 to 15, a name, or "none" to erase

FunctionWhat it does
gfx.size(), gfx.clear([color]){w = , h = } in pixels; erases or fills the drawing
gfx.pixel(x, y, color [, size]), gfx.get_pixel(x, y)draws a pixel (a square); reads one
gfx.line(x1, y1, x2, y2, color [, thickness])a line
gfx.rect(x, y, w, h, color [, fill])a rectangle; fill: true or a border thickness
gfx.circle(x, y, radius, color [, fill])a circle, or a disc
gfx.triangle(x1, y1, x2, y2, x3, y3, color [, fill])a triangle
gfx.fill(x, y, color)paint bucket
gfx.text(x, y, text, color [, scale])text in a 3 × 5 font; returns its width
gfx.image(x, y, rows [, scale [, flip]])a sprite: one hexadecimal colour per pixel, . for nothing
gfx.scroll(dx, dy [, x, y, w, h])moves the drawing, or a rectangle of it

fs

fs · every computer · paths: relative to the current folder, or from the root with /

FunctionWhat it does
fs.list([folder])names of the files and folders
fs.exists(path), fs.is_dir(path)exists? is it a folder?
fs.read(path)the text of the file, or nil
fs.write(path, text), fs.append(path, text)replaces the file, adds at its end
fs.make_dir(path), fs.delete(path)creates a folder; deletes a file or a folder
fs.move(from, to), fs.copy(from, to)moves or renames; copies
fs.size(path), fs.free(), fs.capacity()sizes in bytes
fs.cwd()the current folder: "/" or "/games"

rs, link, display · every computer · sides: front back left right top bottom

FunctionWhat it does
rs.get(side), rs.get_output(side)redstone coming in, going out: 0 to 15
rs.set(side, power)sets an output: 0 to 15, or true / false
rs.sides()the list of the six sides
link.set(item1, item2, power)transmits on a Redstone Link frequency
link.get(item1, item2)strength received on that frequency
display.set(lines), display.line(n, text), display.clear()the lines a Display Link reads

peripheral

peripheral · every computer · names: a side ("left"), or type@x,y,z on a Data Cable

FunctionWhat it does
peripheral.list([type])names of the blocks the computer can drive
peripheral.find(type)the first block of that type, ready to use, or nil
peripheral.type(name)the type of a block: "inventory", "kinetic"...
peripheral.wrap(name)a table of the block's methods, or nil
peripheral.call(name, method, ...)calls one method without wrap

net

net · Minicomputer and newer

FunctionWhat it does
net.id()the address of this computer
net.send(id, data [, channel])sends to one computer; false if it is off, out of reach or full (the receiver must be running a program)
net.broadcast(data [, channel])sends to every computer in reach; returns how many got it
net.receive([timeout])⏸ the next message, or nil after timeout seconds
net.computers(), net.networks()computers in reach, Wi-Fi networks in reach
net.wireless()true if a Radio Modem or a Wi-Fi Router is attached

vehicle

vehicle · Personal Computer, Microcontroller, Modern Computer

FunctionWhat it does
vehicle.position(), vehicle.velocity(){x = , y = , z = }, in blocks and blocks per second
vehicle.speed()speed in blocks per second
vehicle.name(), vehicle.on_vehicle()the name of the Create Aeronautics vehicle (or nil); on one?

Blocks

Methods of the tables returned by peripheral.wrap and peripheral.find. Every block also has any.type().

Idioms

The main loop. Wait for any event, act on its name, restart the timer each time it fires:

Brass
local timer = os.start_timer(1)
while true do
  local e = os.pull_event()
  if e.name == "timer" and e.id == timer then
    timer = os.start_timer(1)     -- every second: redraw, read the sensors...
  elseif e.name == "redstone" then
    print("left: " .. rs.get("left"))
  elseif e.name == "click" then
    print("click at " .. e.x .. ", " .. e.y)
  elseif e.name == "char" and e.char == "q" then
    break
  end
end

Clamp and map a value. A redstone strength (0 to 15) to a speed (0 to 256 RPM), never out of range:

Brass
local function clamp(x, low, high)
  return math.max(low, math.min(high, x))
end
local rpm = clamp(math.floor(rs.get("back") * 256 / 15), 0, 256)

Wrap a block, and check it is there:

Brass
local vault = peripheral.find("inventory")
if vault == nil then error("no inventory found") end
print(vault.count("minecraft:iron_ingot") .. " iron ingots")

Save and load settings as key=value lines (values come back as text):

Brass
local function save(path, settings)
  local lines = {}
  for k, v in pairs(settings) do table.insert(lines, k .. "=" .. tostring(v)) end
  fs.write(path, table.concat(lines, "\n"))
end

local function load(path)
  local settings = {}
  local text = fs.read(path)
  if text == nil then return settings end
  for line in string.split(text, "\n") do
    local eq = string.find(line, "=")
    if eq then settings[string.sub(line, 1, eq - 1)] = string.sub(line, eq + 1) end
  end
  return settings
end

save("settings", {target = 128, mode = "auto"})
print(tonumber(load("settings").target) + 1)
Screen
129

Send and receive (Minicomputer and newer):

Brass
-- the depot
net.broadcast({item = "minecraft:iron_ingot", count = 64}, "stock")

-- the control room
while true do
  local m = net.receive()
  if m.channel == "stock" then print(m.data.item .. ": " .. m.data.count) end
end

Catch an error instead of stopping:

Brass
local r = pcall(fs.write, "log", "pressed: 12")
if not r.ok then print("could not save: " .. r.error) end

Events

Events · local e = os.pull_event(), then e.name and the fields:

EventFields
redstonenone: read rs.get(side)
timerid
keykey: enter backspace delete up down left right home end tab
charchar: the character typed (letters, digits, space)
pastetext
click, dragx, y (character), px, py (pixel), button (1 left, 2 right, 3 middle), source ("terminal" or "monitor")
messagesender, channel, data, via ("cable", "radio", "wifi"), distance
linka, b, power
diskinserted
your owndata

Keys

Keyboard

KeysWhat they do
Ctrl+Tstops the program
Ctrl+Rreboots the computer
Ctrl+Vpastes
Esccloses the terminal (the program keeps running)
↑ ↓ at the promptthe previous commands
Tab at the promptcompletes commands and file names
Ctrl+S in the editorsaves
Ctrl+Space in the editorcompletion
Ctrl+/ in the editorcomments the lines

Numbers to remember

Limits

NumberMeaning
20 ticksone second
256 RPMfull speed of a computer
0 to 15redstone strength
256events waiting, timers waiting
200calls inside each other
65,536characters in a string
32characters in a file name or a label
1,024files and folders on a medium
6 × 9pixels in a character