Core IO

io provides console output and explicit input polling. The prelude exposes its namespace without a dependency clause, while templates handle value formatting before text crosses the output boundary.

Choose the explanation level: Console and input

Console and input

io gives your program console output and input polling. The prelude makes io available without a dependency clause, so you can start writing output right away.

Writing to the console

Console helpers take one string and write it to the output surface.

io.print("loading...")
io.line("Hello")
io.debug("debug details")
io.warn("warning")
io.error("error")

io.line writes a complete line. io.print writes text without ending the line. The browser console shows every call as its own entry, so the two look the same there.

Formatting values

Console helpers accept strings only. Use a template to interpolate values into text before output.

name = "Priya"
io.line([: Hello, [name]])

count = 3
io.line([: count = [count]])

Reading input

Input polling lives under io.input.*. Create an input handle, update it each time your program runs, such as once per tick of an update loop, then close it when done.

input ~= io.input.new()!

io.input.update(~input)

if io.input.key_pressed(input, "d"):
    io.line("pressed d")
;

io.input.close(~input)

io.input.new() can fail when the host does not support input. update and close need mutable access, so they use ~. Polling reads such as key_pressed use shared access.

Each update takes a snapshot of the input since the previous one. Reads return that snapshot until the next update, so a key pressed and released between two updates still reports both. If the window loses focus, held keys and buttons are released at the next update.

The handle records input between updates, but recording input doesn't run your program. A loop that waits for a key press never sees one, because the browser can't deliver events while your code is running.

Pointer input

Pointer helpers report button state and coordinates.

if io.input.pointer_down(input, "left"):
    x = io.input.pointer_x(input)
    y = io.input.pointer_y(input)

    io.line([: pointer [x], [y]])
;

Buttons use "left", "middle" and "right". Coordinates are F64 values measured from the top-left of the page's visible area, with Y increasing downward.

io.set_title is an accepted queued helper that sets the title of the current host surface, such as the browser document title. It takes one String and returns no source-visible result. Reachable calls on hosts without a title capability are rejected before lowering. See Core IO advanced for the capability contract.

For the full contract including host capabilities, backend behaviour, teardown rules and scope boundaries, see Core IO advanced.

@core/io is Moth's broad, high-level host IO package. It owns console output, global input polling and the queued title helper. The prelude injects the bare io namespace as a compile-time alias to @core/io, so normal source files can call io.line(...) without an explicit dependency clause. An explicit @core/io clause binds the same io namespace. An alias such as @core/io as output creates a file-local namespace name.

@core/io belongs to the binding-backed Core package family. It exposes free functions and one opaque type. It does not expose source-defined receiver methods. See Package origins and backing for origin and backing rules.

Host capabilities

Each io operation describes what the program wants from its environment, not the platform API that provides it. io.set_title("Editor") means "set the title of the current user-facing host surface". A browser host realises that as the document title and a native application host could realise it as its window title.

Every operation still has one observable Moth contract. A backend chooses how to realise that contract but can't redefine it. A host that can't provide a capability rejects reachable calls through normal target validation.

io favours a simple, opinionated surface for common tasks over the most flexible or lowest-level API for each capability. Related operations share a namespace such as io.input. io is the only Core package in the prelude because ordinary programs need these interactions immediately. See Prelude policy.

Relationship to focused packages

io may offer the convenient common operation of a domain that a focused package covers in detail. It doesn't duplicate that package's complete API or reimplement its semantics, and both use the same underlying owner where practical. @core/time owns Duration, TimeMark and Timestamp, so io doesn't provide a second set of time values. Targeted browser input belongs to future @builder/web/* packages, while io.input provides a portable global view.

Console helpers

Console helpers write string content to the host's output surface. Each helper takes one String value and returns nothing.

Helper

Output lane

io.print(text)

text without requesting line termination

io.line(text)

text as a completed line or output record

io.debug(text)

debug-level output

io.warn(text)

warning-level output

io.error(text)

error-level output

Hosts preserve the content and order of every call. A stream-oriented host such as a terminal can realise print and line as an ordinary write and a write followed by a newline. A record-oriented host such as a browser console shows each call as its own entry, so print and line look the same there. Moth doesn't buffer output to join print calls or render a newline the host doesn't show.

The output boundary accepts String values only. Templates produce String values, so template interpolation provides the way to format non-string content for output.

io.print("loading...")
io.line("Hello")
io.debug("debug details")
io.warn("warning")
io.error("error")

name = "Priya"
io.line([: Hello, [name]])

count = 3
io.line([: count = [count]])

Passing a non-string value directly to a console helper fails at the output boundary. Interpolate the value into a template first.

Input polling

Input polling lives under io.input.*. The handle type io.input.Input stays opaque. Pass it to the input functions. Do not construct it with struct syntax or inspect its fields.

The host owns the listeners that observe keyboard and pointer events and records their effect inside the handle. Moth never receives a host callback. A program observes recorded input only through explicit update and query calls, which run synchronously like any other call.

io.input.new() returns Input, Error! because input support can be unavailable. A host without the facilities input polling needs returns builtin error code 1, Unsupported, through Error!. update and close require mutable access through ~. Polling reads use shared access.

input ~= io.input.new()!

io.input.update(~input)

if io.input.key_pressed(input, "d"):
    io.line("pressed d")
;

if io.input.pointer_down(input, "left"):
    x = io.input.pointer_x(input)
    y = io.input.pointer_y(input)

    io.line([: pointer [x], [y]])
;

last_key = io.input.last_key_pressed(input)

if last_key is |key|:
    io.line([: last key: [key]])
;

io.input.close(~input)

Snapshots and transitions

io.input.update(~input) publishes a snapshot and is the only point where observable input state changes. Every read observes the snapshot from the last completed update, including held keys, held buttons and pointer coordinates. Repeated reads without an update return the same answers. Before the first update, boolean reads return false, optional reads return none and pointer coordinates are 0.0.

  • key_down and pointer_down report whether a key or button was held at the last update.
  • key_pressed and pointer_pressed report at least one up-to-down transition since the previous update.
  • key_released and pointer_released report at least one down-to-up transition since the previous update.
  • Pressed and released can both be true in one snapshot. A key pressed and released between two updates reports both and isn't down.
  • Holding a key produces one press, however many repeat events the host sends.
  • last_key_pressed, last_key_released, last_pointer_pressed and last_pointer_released return the most recent transition of their kind since the previous update, or none.

Each update clears the transitions it published and keeps held state. The handle records whether each key or button changed, not how often, so its storage depends on the distinct keys and buttons involved rather than the number of host events. Polling doesn't provide an ordered history of events.

When the host surface loses focus or becomes hidden, every held key and button is released. The releases appear at the next update like any other transition. Pointer coordinates keep their last value.

Polling and execution

Recording input doesn't schedule Moth execution. Input that arrives after Moth returns control to the host stays in the handle until something runs Moth code again, such as the next tick of a host-driven update loop, and that code calls update.

A loop that polls until input arrives never observes it. On HTML-JS the browser can't deliver events while Moth code runs, so the loop blocks the delivery it waits for.

Keyboard helpers

Keyboard helpers track down, pressed, released and last-transition states.

Helper

Signature

Access

key_down(input, key)

Input, String -> Bool

shared

key_pressed(input, key)

Input, String -> Bool

shared

key_released(input, key)

Input, String -> Bool

shared

last_key_pressed(input)

Input -> String?

shared

last_key_released(input)

Input -> String?

shared

Keys use logical names. ASCII letters A to Z normalise to lowercase in recorded input and in queries. Other key names keep the host's spelling, including non-ASCII letters, with no Unicode case conversion. Space uses "Space". Special keys use logical names such as "ArrowLeft", "Enter", "Escape", "Backspace" and "Shift".

A key releases under the name it had when pressed. Pressing 1, then Shift, then releasing both reports "1" and "Shift" as released, never "!". Two keys that share a name, such as left and right Shift, keep that name down while either is held.

Pointer helpers

Pointer helpers track button state and position.

Helper

Signature

Access

pointer_down(input, button)

Input, String -> Bool

shared

pointer_pressed(input, button)

Input, String -> Bool

shared

pointer_released(input, button)

Input, String -> Bool

shared

pointer_x(input)

Input -> F64

shared

pointer_y(input)

Input -> F64

shared

last_pointer_pressed(input)

Input -> String?

shared

last_pointer_released(input)

Input -> String?

shared

Pointer buttons use "left", "middle" and "right". Other buttons record no transitions.

Pointer coordinates are F64 logical host-client coordinates. The origin is the top-left corner of the host surface's client area, X increases rightward and Y increases downward. HTML-JS uses viewport-relative CSS pixels from the pointer event's clientX and clientY. A native host may use equivalent window-client logical coordinates. Canvas-local, physical-pixel and DPI-scaled coordinates belong to specialised APIs.

Teardown

io.input.close(~input) stops observing input, clears every recorded and published state and leaves the handle permanently inert. Call it when the input handle no longer needs polling. The handle requires mutable access for close because teardown mutates the underlying host state.

Calling close again or calling update after close does nothing. After close, boolean reads return false, optional reads return none and pointer coordinates return 0.0. Input the host delivers after close can't change those answers.

Teardown is explicit. Host garbage collection doesn't define when a handle stops observing input.

Queued title helper

Accepted queued design. io.set_title(text) takes one ordinary shared String, returns no source-visible value and has no recoverable error channel.

[$in title:Initial title]

io.set_title("Loaded")

The call sets the title of the current user-facing host surface to exactly the supplied String content. HTML-JS realises it as the live document title. It does not reapply the initial title prefix or postfix, mutate builder slot metadata, change the route or rewrite the static output file.

Initial document metadata comes from a direct root builder slot, not from io.set_title.

A stable binding identity carries a title-capability requirement in per-function link facts. HTML-JS will supply that capability through the browser document title. A standalone or embedded JavaScript host is eligible only when it explicitly supplies the same host contract. The existing whole-module HTML-Wasm path rejects reachable calls before lowering. Later mixed output may keep the call on its JavaScript side through ordinary affinity rules, without a Wasm title bridge in this work.

Emit the helper only for reachable calls on a capable host and use Moth's canonical String-content conversion. An unreachable call or one removed by ordinary static specialisation contributes no target requirement, but its source is still frontend-validated. A host missing a facility it advertised violates its host contract. Unsupported hosts never receive a silent no-op.

Backend behaviour

HTML-JS maps console helpers to the browser console, one entry per call, and input helpers to global keyboard and pointer listeners on the browser window. HTML-Wasm rejects reachable Core IO calls before lowering until it gains equivalent support.

Unsupported source forms

  • Do not construct Input with struct syntax.
  • Do not inspect Input fields directly.
  • Do not pass non-string values to console helpers.
  • Do not pass the io namespace record itself as a runtime value.
  • Direct symbol-path clauses such as @core/io/line face rejection. Use direct selections or a namespace clause.

Scope boundaries

Operations that wait, suspend or run Moth code later need structured async and a host-ingress contract. They include sleep, timeouts, intervals, frame callbacks, event waits, fetch and network IO, WebSocket and server-sent events, listeners that call into Moth and asynchronous file selection or image loading. io provides no synchronous-looking forms of them and no general callback mechanism.

Browser-specific event control belongs to future @builder/web/* packages. This covers targeted DOM and canvas input sources, propagation, default suppression, composition and IME events, clipboard access and drag and drop.

Complete filesystem, path and networking APIs belong to focused packages. io may later offer a few common high-level file operations.

Further global input is deferred: a physical key or scancode API, typed key and button values, modifier state, wheel scrolling, pointer deltas, focus queries, touch gestures, gamepads, pressed and released collections and an ordered event queue. Non-JS lowerings are also deferred. See progress matrix for current target availability.

Related concepts