Skip to content

Latest commit

 

History

History
224 lines (167 loc) · 10.6 KB

lua.md

File metadata and controls

224 lines (167 loc) · 10.6 KB

Lua reference

Computers boot into wasmCraft OS, a Lua environment modelled on ComputerCraft's. Most CC programs run unchanged. This page lists what's there, and Differences from ComputerCraft covers what isn't.

The OS runs Lua 5.1 on rilua, with the Lua 5.2 library behaviour CC programs expect: table.pack and table.unpack, load with an environment, string.rep with a separator, and math.log with a base. Lua 5.2 syntax (goto, \x escapes) is not available.

The OS itself is Lua in /rom: /rom/bios.lua builds the APIs, /rom/apis holds the ones loaded as globals, and /rom/programs holds the shell's programs. Reading them is the fastest way to see exactly what a function does.

Globals

Function
print(...) Writes its arguments and a newline, wrapping and scrolling.
write(text) Writes text at the cursor, wrapping words.
printError(...) print in red.
read([replace [, history [, complete [, default]]]]) Reads a line. replace masks each character (for passwords).
sleep(seconds) Waits. Other events that arrive meanwhile are dropped.
loadfile(path [, env]), dofile(path) Load or run a file.
require(name) Loads name.lua or name/init.lua from the root folder, then from /rom/modules/main.
load(chunk [, name [, mode [, env]]]) Lua 5.2's load.

os

Function
os.pullEvent([filter]) Waits for an event and returns its name and parameters. Stops the program on terminate.
os.pullEventRaw([filter]) The same, but returns terminate like any other event.
os.queueEvent(name, ...) Adds an event to this computer's queue.
os.startTimer(seconds) Returns an ID. A timer event with that ID arrives after seconds.
os.cancelTimer(id)
os.setAlarm(hour) Returns an ID. An alarm event arrives at that in-game hour (0 to 24).
os.cancelAlarm(id)
os.clock() Seconds this computer has run, counted in game ticks.
os.time([kind]) "ingame" (the default): the hour of the in-game day, 0 to 24. "utc" or "local": seconds since 1970. Given a date table, the seconds since 1970 for that date.
os.day([kind]) The in-game day, or days since 1970.
os.epoch([kind]) Milliseconds: in-game, or since 1970.
os.date([format [, time]]) Formats a time, strftime-style. "*t" returns a table. Always UTC.
os.getComputerID(), os.getComputerLabel(), os.setComputerLabel(label)
os.shutdown(), os.reboot()
os.run(env, path, ...) Runs a program in an environment.
os.loadAPI(path), os.unloadAPI(name) Load a file's globals as an API table.
os.exec(path) Runs a WebAssembly program in place of the OS. The OS boots again when it ends. The wasm program calls this.
os.version() "wasmCraft OS 0.1".

term

The terminal is 51 × 19 characters on a computer and 39 × 13 on a turtle, with 16 colours.

write, blit, clear, clearLine, scroll, getCursorPos, setCursorPos, getCursorBlink, setCursorBlink, getSize, isColour, getTextColour, setTextColour, getBackgroundColour, setBackgroundColour, getPaletteColour, setPaletteColour and getLine work as in CC. American spellings work too.

term.redirect(target) sends output to another terminal, such as a monitor or a window, and returns the previous one. term.current() and term.native() return the current and the computer's own terminal. term.nativePaletteColour(colour) returns a colour's default RGB.

display

Programs can show an image in place of the text.

Function
display.present(width, height, pixels [, options]) Shows an image. pixels is a string, row by row: four bytes per pixel (RGBA), or one byte per pixel when options.palette is set.
display.clear() Returns to the text.

options.palette is a string of up to 256 RGB triples. options.aspect is how wide the image shows per unit of height (Doom uses 4/3); without it, pixels are square. Images can be up to 1024 pixels on a side and 1 MiB of pixel data. The image clears when the program ends.

colors and colours

The 16 colours as bit flags (colors.white is 1, colors.black is 32768), with combine, subtract, test, toBlit, fromBlit, packRGB, unpackRGB and rgb8.

keys

Key codes for key and key_up events, such as keys.enter and keys.leftCtrl, and keys.getName(code). Codes follow CC: Tweaked's.

fs

Paths are relative to the root, /. /rom is read-only. Mounted floppies appear as disk, disk2, and so on.

list, exists, isDir, isReadOnly, getSize, getFreeSpace, getCapacity, getDrive, makeDir, delete, move, copy, attributes, combine, getName, getDir, isDriveRoot and find (with * and ? wildcards).

fs.open(path, mode) opens a file in mode "r", "w" or "a", with "b" for binary. It returns a handle with readLine, readAll, read, write, writeLine, flush, seek and close, as its mode allows.

A computer has 1,000,000 bytes of storage and a floppy has 125,000.

io

Lua's io library on top of fs: io.open, io.lines, io.read, io.write, io.input, io.output, io.type and io.close. File handles have read, lines, write, seek, flush and close.

textutils

serialize and unserialize (Lua tables as text), serializeJSON and unserializeJSON, formatTime, slowWrite, slowPrint, tabulate, pagedPrint, urlEncode and complete.

settings

Named settings saved to /.settings, which the computer loads when it boots: define, undefine, set, get, getDetails, unset, clear, getNames, load and save. The set program lists and changes them.

parallel

parallel.waitForAny(...) and parallel.waitForAll(...) run functions side by side as coroutines. Each gets every event.

peripheral

Peripherals are the blocks touching a computer, named by side: top, bottom, left, right, front and back, relative to the way the computer faces. A turtle's equipped modem is a peripheral on the side it's equipped on.

Function
peripheral.getNames() The sides with something attached.
peripheral.isPresent(side), peripheral.getType(side) Types are "modem", "monitor" and "drive".
peripheral.getMethods(side)
peripheral.call(side, method, ...)
peripheral.wrap(side) A table with the peripheral's methods.
peripheral.find(type [, filter]) Every attached peripheral of a type, wrapped.
peripheral.getName(wrapped) The side a wrapped peripheral is on.

The methods of each peripheral are in Peripherals and Networking.

redstone

redstone (also rs): getSides, getInput, getOutput, setOutput, getAnalogInput, getAnalogOutput and setAnalogOutput, by side. Analog levels are 0 to 15. A redstone event arrives when an input changes. See Peripherals.

turtle

On turtles only. See Turtles for every function.

rednet and gps

See Networking.

disk

disk.isPresent, hasData, getMountPath, getLabel, setLabel, getID and eject, by the drive's side. See Peripherals.

window, paintutils, vector

  • window.create(parent, x, y, width, height [, visible]) makes a terminal inside another, with setVisible, redraw, reposition, getPosition and the rest of the terminal methods.
  • paintutils: parseImage, loadImage, drawPixel, drawLine, drawBox, drawFilledBox, drawImage.
  • vector.new(x, y, z) with add, sub, mul, div, dot, cross, length, normalize, round and arithmetic operators.

bit32, bit, utf8

bit32 as in Lua 5.2, CC's older bit, and utf8 (char, codes, codepoint, len, offset).

shell

Programs run by the shell can use shell.run, shell.execute, shell.resolve, shell.resolveProgram, shell.dir, shell.setDir, shell.path, shell.setPath, shell.aliases, shell.setAlias, shell.clearAlias, shell.programs, shell.getRunningProgram and shell.exit.

Events

Event Parameters When
char character A character is typed.
key key code, is repeat A key is pressed.
key_up key code A key is released.
paste text Text is pasted with Ctrl+V.
terminate Ctrl+T is held.
timer ID A timer from os.startTimer finishes.
alarm ID An alarm from os.setAlarm goes off.
redstone A redstone input changes.
modem_message side, channel, reply channel, message, distance A modem receives a message on an open channel.
rednet_message sender ID, message, protocol A rednet message arrives.
monitor_touch side, x, y A player right-clicks a monitor.
monitor_resize side A monitor's size or text scale changes.
disk side A disk goes into a drive.
disk_eject side A disk comes out of a drive.
task_complete ID, success, results... A world call made by a WebAssembly program finishes. Lua programs never see these.

A computer queues up to 256 events. Past that, new events are dropped until the program catches up.

Limits

Memory 64 MiB per computer.
Running without yielding 7 seconds. Past that, the OS halts with Too long without yielding; hold Ctrl+R to reboot. Pull an event or call sleep(0) inside long loops. Turtle actions yield on their own.
Storage 1,000,000 bytes per computer, 125,000 per floppy.
Event queue 256 events.

Differences from ComputerCraft

  • Lua 5.1 syntax. No goto and no \x escapes. The 5.2 library functions CC programs use are there.
  • No http. Computers have no Internet access. Bring code in on floppies or through the world folder.
  • No peripheral or peripheral_detach events. Check peripheral.getNames() when you need to know what's attached.
  • No wired networks, cables, speakers, printers or pocket computers yet. disk.playAudio and its relatives do nothing.
  • os.date is always UTC, and os.time("local") is the same as "utc".
  • Turtles answer queries at once. getItemCount, getFuelLevel, getItemDetail, select and similar calls return without waiting for a game tick. Only actions that change the world take time.
  • display is new: programs can draw images. CC has no equivalent.
  • os.exec is new: it hands the computer to a WebAssembly program.