# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# proc.builder
What a graph builder hands the author, in the call form: `proc.define(function(g) ... end)`.
- `g.<name>(args)` adds a node of the node asset the name resolves to, by asset identity: the nodebox and the
node's folder name (`g.points.disc`), a path (`g["/zero/source/fx/ring.procNode"]`), `~` (the nearest package,
effect or world root: `g["~/ring"]`), a guid, or a short name (`g.disc`). A path, `~` name or identity ending in
`.procNode` or `.procGraph` names an asset of that kind alone; one without the suffix names either, so where a
node and a part share a name it states the suffix. A name that matches two nodes, and a name that matches none,
are errors that name the candidates. Each call is recorded in the graph by the node's
guid. Arguments are a table naming inputs or positional values in the node's input order.
- What a call answers: a node with one output answers that output's socket, a node with several answers a
record of sockets by output name (`local f = g.core.normals.face(geo); f.geometry, f.area`), a node with none
answers nothing. The record does not depend on declaration order. The record handed whole to an input that
takes one value is refused where it is handed, naming the outputs to read (`.value`, `.report`).
- A name is called this way only for a node written in the call form (`builder.callsByName(path)` says which). A
name no node answers to is refused naming the nearest names a call resolves.
- A node's own source reaches its package's modules and assets with `require("~.<name>")` and
`asset.resolve("~.<name>", type)`: `~` there is the nearest `.package` folder, wherever the node sits in it.
- `g.op.<name>(args)` (and `proc.op.<name>`) adds a node of an op, for library nodes built on the ops. An op that
is a graph built with `g:node` (the `procNodes/` of the procgen package, registered under their graph ids) is
refused at the call, naming its folder and the node written in this form that answers to the same name
(`'g.op.points.filter' is .../procNodes/pointsFilter.procNode, a graph built with g:node, ...; call
g.points.filter`). An id no op carries is refused naming the ops that start the same way.
- `g:input(name, default, opts)` is typed by the default: `Float`, `String`, `Bool`, `Vec3`, `Color`, `List<T>`,
`Record` with its fields. `opts` takes `min`, `max`, `options`, `description`, `optional`, `plain` and `type` for a
default that does not state its type or no default at all. An empty table default with a stated `type` is that type's
empty value (`g:input("entities", {}, { type = "List<Entity>" })`). A vector written as a plain table reads its
components by name whichever form it was written in, the reading an op's params take: `{ 0, 0, 0, 1 }` answers `.w`,
and a pair (`{ a, b }`, `{ x, y }` or `{ x, z }`) answers its second component as `.y` and as `.z`.
- An input declared `plain = true`, an input with `options`, and an input of type Bool or String is a plain value
while the graph is built: `g:input` answers the value itself, `if`, comparisons and loops over it are allowed, and
it passes into calls as a constant. `plain = true` is how a count, a vector, a record or a list that chooses the
graph's structure is declared (`g:input("storeys", 5, { type = "Int", plain = true })`, `g:input("edges",
{ { bays = 3 } }, { plain = true })`): the graph is built again for each value it is given, it is not animated, and
it takes no per-element field. Any other number and vector input is a socket, which changes without a build and
takes animated values and fields. A table value reaches the build as a frozen copy. The graph records the plain
values it was built with in `graph.plain`, and each such declaration in `graph.inputs[name].plain = true`.
- Sockets take `+ - * / % ^ // ..` and unary minus, `math.*` and `vector.*` (each a `math.<name>` node;
`vector.create` over sockets is `math.vec2`, `math.vec3` or `math.vec4` by its component count), `x.name`,
`x.name = v` and `x[name] = v` for a computed name (which rebind `x`), `x[class][name]`, `x[n]`, and
`for index, item in list do ... end`. A source loaded
through `builder.prepareSource` reads plain `math`, `vector` and `rand` over sockets unchanged; `define` loads a
node or graph entry that way when it names them.
- `vector.create` has the width of its component count whether its arguments are sockets or numbers: two numbers
answer the Vec2 value `{ x, y }` and four the Vec4 value `{ x, y, z, w }` (what `math.vec2` and `math.vec4` make
of numbers), and three a Luau vector. `orient = vector.create(0, 0, 0, 1)` writes a Vec4 column.
- `g.compare(a, op, b)`, `g.where(cond, a, b)`, `g.pick(choice, alternatives)`, `g:fold(n, init, fn, opts)`,
`g:state(name, columns)`, `g:step(dt, substeps, fn)`, `g:check(cond, message)`, `g.has(geometry, class, name)`
and `g.copy(socket)` record the constructs the evaluator knows.
- `g:state(name, columns)` states the columns a step keeps, `{ [name] = { type, count } }`, as values the plan knows:
literals and inputs, records and lists of them, and what constructs and a `pure` `io.luau` call make from them. A
pure call's answer stands even when its arguments are cooked (a call reading the attribute names of a source's
points), so a `for` over its answer may add a column per name (`schema["s_" .. name] = specs[name]` over
`specs.keys`), and a step body writes them by the same names.
- `g:check(cond, message)`: a `cond` known while the graph is built refuses the build with the message (a true one
records nothing); a `cond` that reads a socket is recorded for the plan or the cook to answer. The build of a
node's own defaults, which is what indexes the node, holds such a refusal instead of raising it (`graph.refusals`),
and `forInputs` states it where the node is called or cooked as it stands, so a check over a plain input fires when
the call gives it the refused value.
- A plain Luau table filled inside a `for` body over sockets keeps one element (`rings[#rings + 1] = v`,
`table.insert(rings, v)`): the body is one pass for every item. `builder.check` refuses it with the code
`socket-loop-append`, naming the form to write: a local declared before the loop and assigned inside it, read after the
loop, where it is the list of every pass's value.
- `g.copy(value)` of a record or a list written in the graph (`g.copy({ total = 0 })`) is a value of its own that
member writes rebind, so a `for` body that fills it carries it from pass to pass.
- A class view made with a socket key (`names[i]`) and read as a value is a node of the scope it was made in, whichever
loop body first reads it.
- A `for` body is one pass that stands for every item. `index` is the item's place (a socket, from 1). A value built
outside the body that the body reads or assigns (`geometry[class][name] = v`, `record.name = v`,
`record[name] = v`) is carried: each pass starts from what the pass before left, the first from the value as it
stood before the loop, and after the loop the value is what the last pass left. The loop records the carries in
`scope.carries[id] = { init, result }` and the refs `loop_index`, `loop_carry` (the value at the start of a pass)
and `loop_result` (the value after the loop). A value the body only reads reads as it was. The emitter writes a
carrying loop as it was authored: a local that starts as `g:copy(value)`, the body's assignments to it, and the loop
reading that local after it (`proc.emit`).
- `g.clock.placement` (16 numbers, column after column), `g.clock.inverse`, `g.clock.rotation` (`{ x, y, z, w }`)
and `g.clock.entity` answer where the graph stands in the scene it is cooked in: each is a `construct.scene` node
that reads the scene the cook is handed (a graph standing on no entity has the identity placement and no
entity). `g.transform.point(p)`, `g.transform.direction(d)` and `g.transform.rotation(q)` carry a world position,
direction or quaternion into the graph's space through the inverse placement; each takes plain values, sockets or
Fields.
- `g:fold(n, init, fn, { stop = "changed" })` or `{ stop = function(before, after) return <Bool> end }`; `fn` returns
the state only. The fold runs `n` passes and ends early at the first pass whose stop holds.
- `g.element` is the element a Field evaluates over: `g.element.id` (Int), `g.element.P` (the position leaf that
`fieldc.withPosition` substitutes, also written `g.element.point.P`) and `g.element.<class>.<column>` for a column
of the domain the field stands in. Each read is a socket, so `g.element.id * 1.0` is a math node.
- `rand.unit(seed, ...scope, id)` (a global in a node source, also `builder.rand.unit`) is the Float field of unit
draws keyed by the seed, the scope (`graphId, nodeId, channel`, or `graphId, compositePath, nodeId, channel`) and
the element `id`, last (`g.element.id`). It adds an `io.luau` node
`{ module = "@builtin::systems.procgen.proc.fieldc.leaves", fn = "rand", args = { seed, { ...scope }, id },
returns = { "Any" } }` and answers its `value`.
- `geometry.names[class]` lists the attribute names a class holds (a list socket the plan answers);
`geometry[class].count = n` assigns the domain count, so `count` is no column's name (a value per element written
under it is refused); `geometry.material = m` assigns the material. `names` is
read by that name on any socket: what is read off it by a class (`geometry.names.point`) lists the names, and any
other read (`record.names[2]`, `record.names`) is the member a record holds under that name, as `count` and `keys`
are. `material` is assigned by that name on any socket.
- A member, an item, a column or the names of a value built outside a fold, step or stop body that the body reads
first is a node of the scope the value was built in: the body and every later fold read the one value, which the plan
writes once. A read keyed by a socket of the body (a fold's index) stays in the body.
- `g.clock.time`, `.frame`, `.delta` and `.duration` are sockets; `.fps`, `.frames`, `.loop` and `.realTime` are the
timeline's values.
- Luau's `< <= > >= == ~=` over a socket, and `and`, `or`, `not`, `if` and `while` that test one, have no value
while the graph is built. `builder.check(source)` names each one with the `g.*` form to write, and `define` holds a
node or graph entry to it. `and` and `or` test their left operand alone, so `plain or socket` passes. The check
follows names block by block as Luau scopes them: a local, a loop variable or a function parameter is its block's
own, and a parameter of a function that is not a fold, step or stop body is not known to be a socket (a comparison
over one is refused when the graph is built). Plain inputs are not sockets to the check. A plain Luau table indexed by a socket (`LANES[values.type]`) answers nil
while the graph is built, so the check refuses it with the code `socket-table-index`, which names `g.pick`.
- A list of values holds a nil as a value: `{ a, nil, b }` is three, and the second is a constant of nothing.
## Building a graph for other plain values
A graph whose plain inputs change structure is built again for the values a cook was given.
- `builder.forInputs(graph, inputs)` answers `graph` while its plain inputs hold what the build used, else the graph
built again from `graph.source` with the values `inputs` states (an input it leaves out takes its default); values
are compared by content, a record or a list included, and the result is cached by the source text and the values,
so a node written again is built again. `builder.KEPT_BUILDS_PER_SOURCE` of a source's builds are kept, the ones
used last. A build for other values keeps what the cook already made: only the nodes the new values change cook.
A plain input given an animated value, a per-element field or a value held on the device is refused by name. It answers `nil, reason` when the source cannot be built again or a value
is outside the input's options.
- An optional input with no default (`g:input(name, nil, { optional = true })`) is nil while the graph is built for a
call that leaves it unwired, and its socket otherwise, so `if input == nil then ... end` in a node source is decided
by what the call wired. The declaration states `wiring = true` and the graph records the wiring it was built for in
`graph.wiring[name]`; `forInputs` builds the graph again for a cook given no value for such an input (`values[name]
== false` states none in `rebuild` and `withInputs`).
- `builder.rebuild(graph, values)` builds again unconditionally; `builder.withInputs(values, fn)` runs a function
that calls `proc.define` and gives that graph the values. A node asset called with a plain value records it as a
constant param; the evaluator reads a node's graph through `forInputs` with those params.
## What a build resolves once
A build resolves each name once. The first call of a name `g.<name>(...)` in a build finds the node asset the name
answers to; the build keeps the asset, its inputs and outputs, and the envelope its calls record, and every later call
of that name in the same build takes them. Each `building` frame (a graph source, or a node source loaded by a call)
holds its own, by the graph's source and the name, on the thread that runs the build; the memo ends with the frame, so a
node written between two builds is resolved again by the next, and builds on other threads share nothing. The `Info` of
a node asset is kept by the node graph it was read from, and the line of each call is kept as a number that `siteOf`
states as `path:line` where it is read. `builder.setResolveMemo(false)` switches all three off for the builds after
(the answer is the setting before), and `builder.resolveCounts()` answers the calls that resolved a name (`resolved`)
and the calls a kept answer served (`hits`).
## What a build is made against
A graph source that has a base is built against it. The base of an entry source is the graph the last
`proc.takeHandOff` of its folder gave a Generator (`builder.setBase(graph)`, `builder.baseOf(entry)`), held weakly.
When the run of a build ends, a pass compares every node the run made with the base's node of the same id (`compareNode`
of `proc.eval.replan`, and the node's `op` field by field). A node that is equal is replaced in `graph.nodes` by the
base's own table, which is frozen, along with the tables under its inputs and params; a node that differs, or that the
base does not hold, is frozen where it is. The scopes are compared and the ones that differ are listed; they stay the
build's own tables. The graph states the result in `_diff`: `changed` (the ids of the nodes that differ or are new),
`removed` (the ids of the base's nodes the build did not make), `scopes` (the ids of the scopes that differ), `added`,
the counts of the nodes and scopes, `against` (the base, held weakly) and the edit counts of both graphs when the pass
ran. The planner (`replan.dirty`) reads it while the graph and the base stand as they did then, and compares only the
nodes it lists.
- A node that keeps the base's table keeps the place the base gave it in the order the nodes were made in. When this
build made it elsewhere, the graph states the new place in `_moved`; `builder.seqOf(graph, id)` answers the place a
node holds, and `graph:toJSON()` states the nodes with it (`builder.documentNode(graph, id, node)` is one node as the
document states it), so a document and an emitted source are those of a build that made every node itself.
- A table two graphs share is frozen, so a write into one raises. `proc.edit` replaces a node it writes into by a copy
of its own (the node, its `inputs` and its `params`) before it writes, and `builder.againstCounts()` counts those
copies beside the passes run (`passes`), the nodes filed from the base (`reused`), the nodes listed (`changed`) and the time the passes took (`ms`).
- `builder.setBuildAgainstBase(false)` switches the pass off for the builds after (the answer is the setting before).
A build of a source with no base, a build for other plain values (`forInputs`, `rebuild`) and a build of a node asset
are the graph their run made.
## What a build reads
A node or graph source is compiled with `builder.compile(src, "@" .. entry)` and run as a build with
`builder.building(entry, fn, ...)`. While a build runs, the source sees a `vfs` whose `read`, `readAsync` and
`readBounded` note each file for that build, and `builder.read` (`proc.read`) notes a file read from a module the
build calls into. When the build ends, the files it read are recorded against its entry source, replacing what its
earlier builds read: `builder.readsOf(entry)` lists them and `builder.readersOf(file)` the entry sources whose last
build read a file. A write of such a file is a `proc.sourceChanged` of each of those sources. `builder.forget(folder)`
drops the source text and the built graph the builder holds for a node or graph, so the next build that reaches it
runs its source again. The modules a build requires are recorded by the engine, which tells the node or graph type
through `onDependencyChange` when one of them re-runs.
## The wiring of each run of `graph.module`
`graph.module` binds its wiring into the builder (`builder.bind`) each time its body runs, with the metatable of the
graphs that run makes as `helpers.graph`, and the builder keeps that wiring on the metatable. A graph is wired by the
run that made it: `builder.run` declares its outputs, a value is wired into its refs, and `rebuild` builds an inline
graph again, each through the wiring of the graph's own run. The body runs again whenever the require cache lets go of
the module while a module that took its functions keeps them (`proc.define` is `graph.module`'s `define` as `proc`
loaded it), as a reset of the scripting state to a mark taken before the module loaded does; the graphs of both runs
are then built side by side.
## What a graph records
A call-form graph states `surface = "call"`. Each node it makes carries `call = true`, `seq` (the order it was made
in, which the emitter writes it back in) and `scope`. A node asset is `op = { __ref, type = "procNode", name }`; an
op is its id string; a construct is `op = "construct.<kind>"` with `construct = <kind>`. `graph.scopes` holds each
`for`, `fold`, `stop` and `step` body, `graph.states` each `g:state`, `graph.plain` the plain input values.
Each call and scope also records the line of the graph's source it was written on, `path:line`
(`builder.siteOf(graph, id)`), in a table the graph's document leaves out, so where a call sits moves no hash. The
plan carries it onto each call it writes out (`plan.flat.origins[<flat id>].site`, the graph's own calls in
`plan.flat.sites`), and a cook's failure is read at it: `describeFailure(flat, err)` of the eval module
(`@builtin::systems.procgen.proc.eval`) answers
`<path>:<line>: g.<call> failed: <why>`, the line being in the deepest source the person can edit.
The `inputs` of a construct node are refs (a constant is `{ kind = "const", value }`); `params` are constants.
| construct | inputs | params | answers |
|---|---|---|---|
| `member` | `value`, `name` | | the member of `value` |
| `member_set` | `value`, `name`, `to` | | `value` with the member written |
| `item` | `list`, `index` | | the item |
| `column` | `geometry`, `class`, `name` | | the column read (a read of `count` is the domain count) |
| `column_set` | `geometry`, `class`, `name`, `value` | | the geometry with the column written |
| `column_remove` | `geometry`, `class`, `name` | | the geometry without the column |
| `count_set` | `geometry`, `class`, `count` | | the geometry with that class's domain count set to `count`; a value per element is refused (no column is named `count`) |
| `material_set` | `geometry`, `material` | | the geometry with its material set |
| `names` | `geometry`, `class` | | the List of attribute names the class holds, answered at plan |
| `has` | `geometry`, `class`, `name` | | a Bool answered at plan: whether the class holds the column |
| `check` | `cond` | `message` | nothing; a `cond` that is false when cooked is an error stating `message` |
| `compare` | `a`, `b` | `op` (`eq neq lt le gt ge`) | a Bool |
| `where` | `cond`, `a`, `b` | | `a` where `cond` holds, else `b` |
| `pick` | `choice`, `alternatives` | | the alternative the choice names: by option name, by a list position (a false choice the first, a true one the second), or by `false` and `true` keys |
| `step_sample` | `step`, `value` | | the value of an animated `value` at the step's time |
| `step_between` | `step`, `index` | | the fraction (0 to 1) of the step's movement that source `index` of the step has covered; the evaluator defines it |
A call that has several outputs names them in refs: `{ kind = "node_output", node, output = "<name>" }`; a node with
one output has `output = nil`.
### Refs
The v1 refs (`const`, `graph_input`, `node_output`, `list`, `record`, `animated`) and:
| ref | stands for |
|---|---|
| `loop_item { loop }`, `loop_collect { loop, ref }` | the item of a `for` scope, and the list of `ref` over every item |
| `fold_value { scope }`, `fold_index { scope }`, `fold_result { scope }` | the value and the index (from 1) of a fold pass, and the value after the last pass |
| `fold_before { scope }`, `fold_after { scope }` | the state before and after a pass, inside a fold's `stop` function; `scope` is the `stop` scope |
| `step_state { scope }`, `step_index { scope }`, `step_result { scope }` | the state record, the step record (`dt time graphTime index first start`, with `step_sample` and `step_between`), and the state the step reached |
| `state { name }`, `clock { field }`, `engine` | declared state, the clock's field, the engine API namespace |
| `element { field, class? }` | the element a Field evaluates over: `field = "id"` its index, `field = "P"` its position leaf (no class), else the column `field` of the domain `class` |
### Scopes
`graph.scopes[id]` is `{ kind, parent, seq, ... }`:
- `for`: `list`, `item`.
- `fold`: `count`, `init`, `result`, and `stop` when it states one: `"changed"` (the pass ends the fold when the
state it produced equals the one it read) or `{ scope = <id of a stop scope> }`.
- `stop`: a scope whose `parent` is its fold. Its nodes read `fold_before` and `fold_after`; `result` is the Bool
ref the fold stops on. It is evaluated after each pass.
- `step`: `dt`, `substeps`, `result`.
The `plain` table of a graph and the `plain = true` flag of an input declaration state which inputs are build-time
values.
Part of `@builtin::systems.procgen.proc`.
# proc.registry
The operation registry: register/lookup/schema/search/help for procedural ops.
Part of `@builtin::systems.procgen.proc`.
# json
JSON encode/decode library for Luau. Encodes Lua values to JSON
strings and decodes JSON strings back to Lua values. Used for
communication with the Rust side of the engine, the VFS read/write
bridge, and any wire-format that needs JSON.
Pure Luau, no engine dependencies. Compact and pretty-printed
encoders, plus a hand-rolled decoder that streams the input by position
so it works under WASM as well as native.
## Exports
- `Json.encode(value: any, indent?: string, currentIndent?: string) -> string` — compact encode. Functions / unknown types and NaN/Inf encode as `null`.
- `Json.encodePretty(value: any, indentStr?: string) -> string` — pretty-printed encode with sorted object keys (diff-friendly).
- `Json.encodeArgs(...: any) -> string` — encode varargs as a JSON array.
- `Json.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure.
## Usage
```luau
local Json = require("@builtin::modules.json")
local widget = { type = "button", text = "Click Me" }
local compact = Json.encode(widget) -- '{"text":"Click Me","type":"button"}'
local pretty = Json.encodePretty(widget, " ")
local decoded = Json.decode(compact)
local v, err = Json.decode("oops") -- v = nil, err = error message
```
## Notes
- Object keys are sorted alphabetically in both encoders for consistent
output across runs.
- Numeric keys on objects are stringified at encode time (JSON has no
numeric keys). Pure-integer key sets get detected as arrays via
`isArray` and encoded with brackets.
- NaN, +Inf, -Inf encode as `null` — JSON has no representation. Round
trips through `decode` recover `null` (Lua `nil`), so they don't
preserve.
- Unicode `\uXXXX` escapes decode to UTF-8 by hand to stay WASM-safe.
Only the BMP is covered; supplementary planes via surrogate pairs
are not.
- Functions encode as `null`.
- Decode is character-streamed — no regex, no `string.match` patterns
on the whole input — so the line-and-column information needs to be
reconstructed from the position offset.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. |
| `settingsHealed(values, stored)` | On a read, to repair stored values. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in. `asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# proc
Code-authored, graph-backed procedural generation for the Zero engine.
A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by
family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`,
the returned table is the graph's outputs, and `io.output` is how the graph stands in the world.
`builder.module/README.md` holds every rule of that form.
This module owns the whole procedural model: the graph builder + data model,
the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op
implementations. Authored `.procGraph` graphs are persisted via
`procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in
`procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)`
from a script or an agent's `tool_exec` script, or `zero procgen preview` in the
shell. Generated
meshes/materials/textures/bundles are persisted through their own `.assetType`.
An op family can also come from outside this package: a `.procPack` asset
registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones
shipped here (`proc.registerPack(name, ops)` is what it registers through, and
what a test or a tool calls to hold a family for the life of one VM).
`terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/`
and covering a whole landscape; `guides { path =
"systems/terrainSystem/documentation/terrain" }` is its guide.
To find out what the registry holds, use the `procgen` toolbox: `searchNodes`
searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and
`proc.schema(id)` are the same answers in-process, for a graph builder looking
something up while it runs.
# luau_introspect (module)
Parses Luau/asset source TEXT into structured declarations. Pure
string/pattern parsing (`string.find` / `string.match` / `string.gmatch`)
over the literal source — no compiling, no VM spawn, no runtime state, no
engine FFI. Given source text, it extracts what is written in the file.
This is the shared parser every per-assetType `M.ref.inspect` hook uses to
turn a component/module/tool's own source into the structured record
`asset.inspect` returns.
## Exports
- `docstrings(src) -> DocMap` — scans `--!desc` / `--!arg` / `--!return` /
`--!example` comment runs and binds each run to the name of the
declaration on the next non-comment line (the identifier after
`function`, `public:`, `local function`, or `M.`).
- `publicFields(src) -> { FieldEntry }` — parses `public = { name =
Field.<kind>(default, mode), ... }` table-literal entries and
module-scope `public.<name> = Field.<kind>(...)` assignments.
- `events(src) -> { EventEntry }` — parses `events = { name =
Event(payloadSchema?, syncMode?), ... }` table-literal entries.
- `methods(src) -> { MethodEntry }` — parses `function public:<name>(...)`
/ `typed function public:<name>(...)` declarations (params + optional
return type).
- `lifecycleHooks(src, catalog) -> { string }` — top-level `function
<name>(` declarations whose name is in the caller-supplied `catalog`
array.
- `moduleExports(src) -> { ExportEntry }` — parses `M.<name> = function`
assignments, `function M.<name>(...)` declarations, and a trailing
`return { foo = foo, ... }` export table.
- `forSource(src, computeFn) -> any` — memoises `computeFn(src)` keyed on
`src` itself in a module-local table. The same source text returns the
cached result without re-running `computeFn`; different source text
recomputes. Keyed on the source content (not an asset checksum) because
composite/container assets (component folders, scene folders, etc.) all
hash to the empty-string checksum — a checksum-keyed cache collapses
every such asset's detail onto whichever one was inspected first.
## Usage
```luau
local Introspect = require("modules.luau_introspect")
local src = self:getInitScript()
local detail = Introspect.forSource(src, function(s)
return {
fields = Introspect.publicFields(s),
events = Introspect.events(s),
methods = Introspect.methods(s),
hooks = Introspect.lifecycleHooks(s, lifecycleCatalog),
}
end)
```
## Notes
- Every function is a pure string→table transform: same source text in,
same structured table out, every time. No reads of live component
state, no entity/world queries.
- Structural scanning runs over a comment- and string-aware **mask** of
the source (a same-length copy where comment bodies and string-literal
contents are blanked to spaces, delimiters and newlines preserved).
Pattern matches and brace/paren balancing run on the mask — so a brace,
`Field.`, `Event(`, or a whole entry that appears inside a comment or a
string literal never registers — while captured values are sliced from
the original source at the same (aligned) indices. This makes the
parser robust to apostrophes in comments, commented-out entries, string
defaults containing `}` / `Field.` / `Event(`, and `[[ ]]` long
strings.
- `default` / `category` are raw trimmed source-text slices (with any
trailing comment stripped), not evaluated values.
- For a **ref constructor** (`Field.assetRef` / `dataRef` / `resource`
/ `componentRef`) the FIRST positional argument is the category /
contract / componentType selector, captured under `category`; the
SECOND argument is captured under `default`.
- For every **other** Field kind the first argument is the `default`
and `category` is nil.
- A trailing `Sync` / `NoSync` identifier is captured as `sync`,
tolerating a trailing comma or a trailing comment after the last
argument.
- Field/Event entries whose key is a computed or indirect expression
(`[expr] = Field.number(...)`) are omitted — only literal identifier
keys are recognised.
- `methods` captures a `...` variadic parameter (as `name = "..."`), with
its `: <type>` annotation when present.
- A `--!desc` written above a field/event declaration (`<name> =
Field.<kind>(...)` / `<name> = Event(...)`) or a `public.<name> =`
assignment binds to that name in `docstrings`, and is folded into the
corresponding `publicFields` / `events` entry's `desc`.
- `lifecycleHooks` never hardcodes the lifecycle-callback catalog; the
caller passes the list of names to match against.
- `forSource`'s memo is bounded (oldest-key eviction) so a long session
touching many distinct asset versions can't grow it without limit.
# assetType.shared.ref
Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries. Replaces the per-call C metatable that used to live in `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable`.
## Public API
```lua
local assetRef = require("@builtin::assetTypes.assetType.shared.ref")
-- Called by the Rust factory (push_asset_ref_handle) via
-- _G.__build_asset_ref_proxy after the envelope fields are set.
assetRef.build(envelope) -- attaches AssetRefMT, returns the table
```
The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below).
## Method dispatch order
`ref.foo` is resolved in this order:
1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (engine contract from gh#1889).
2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods.
3. **Nil** — unknown key, same shape as the original C metatable.
## Adding methods for a new asset type
Drop a `behavior.luau` into the type folder:
```
src/lua/lib/assetTypes/<typename>.assetType/
├── type.yaml -- structural spec (existing)
├── behavior.luau -- ref + global behaviour (new)
└── template/ -- placeholder body (existing)
```
`behavior.luau` returns:
```lua
return {
ref = {
--!desc Per-instance method on every `<typename>` AssetRef.
myMethod = function(self, ...) ... end,
},
global = {
-- Reserved for the asset.<typename>.* surface — not consumed
-- yet; included so the contract from gh#1889 lands cleanly.
},
}
```
Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined.
## Discovery and hot-reload
Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half.
Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call.
The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods.
## Why Luau, not Rust
The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means:
- Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code.
- Adding a new asset type drops in a new folder; no Rust rebuild.
- Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives.
## Consumers
- `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable` — the Rust factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push.
- Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.
# yaml.module
YAML decode + encode for authored engine content. Pure Luau, no engine
dependencies — a general parsing library, not data-system plumbing.
```luau
local Yaml = require("@builtin::modules.yaml")
local doc = Yaml.decode(vfs.read(path))
vfs.write(path, Yaml.encode(doc))
```
## Supported subset
- Block mappings (`key: value`) and block sequences (`- item`), nested
to any depth.
- Compact sequence-of-mapping entries (`- path: x` / ` kind: y`).
- Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line.
- Plain scalars with type inference: `~` / `null` → nil, `true` /
`false` → boolean, numeric literals → number, everything else →
string.
- Single- and double-quoted strings (`''` escapes a literal quote
inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a
double-quoted one). A quote opens a quoted scalar where a scalar
begins — after `key:`, after a `- ` entry marker, or inside a flow
collection — so a plain scalar carries an apostrophe as data
(`note: the world's rules`). Quoted keys are read in flow mappings.
- `#` comments — honored outside quotes, so a `#` inside a quoted
string is kept as data.
- Literal (`|`) and folded (`>`) block scalars, with a chomping
indicator (`-` strips the final newline, `+` keeps every trailing
blank line, none keeps one newline) and an indentation indicator
(`1`-`9`: the content's indent past the parent's), in either order
(`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text:
quotes (balanced or not), `#`, `key: value` and `---` inside it are
data.
- An optional leading `---` document marker.
## Loud-error contract
Constructs outside the subset above raise instead of misparsing:
anchors/aliases (`&`, `*`), tags (`!`), directives (`%`),
multi-document streams (a second `---`), a block-scalar header
it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and
block-scalar bodies). Every error carries the offending line number
(`yaml: line N: ...`), so a bad config points straight at the line to
fix.
Tab indentation is rejected everywhere — including block-scalar body
lines whose leading whitespace contains a tab. A tab after the first
non-space character of a line is content and passes through.
## API
- `Yaml.decode(text: string): any` — decode a YAML document into a
Luau value (table, scalar, or nil for an empty document). Raises on
malformed input or an unsupported construct.
- `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as
`decode` does, and report whether the text carries a comment by the
decoder's own rule: a `#` at a line's start or after whitespace, outside
a quoted scalar and outside a block scalar. Re-encoding the value drops
such comments, so an editor that writes a document back reads this first.
- `Yaml.encode(value: table): string` — encode a Luau table as YAML
(block style, two-space indent, alphabetically sorted keys). Raises
on values YAML can't represent (functions, userdata, non-string
mapping keys).
A top-level empty table encodes to an empty document, which decodes
back to `nil` (the YAML empty-document ambiguity).
# assetType runtime
The machinery that reads a `<typename>.assetType/behavior.luau` and turns its
declarations into live behaviour.
A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared
code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` /
`onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` /
`settingsCorrections` hooks. None of it runs itself. This is the code that
runs it, and it lives here because reading a type's declarations is the
**assetType type's own behaviour** — the same way `material.assetType` owns
what a `.material` does.
## Sub-modules
| Module | Reads | Responsibility |
|---|---|---|
| `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. |
| `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. |
| `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. |
| `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. |
| `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. |
| `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. |
| `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. |
| `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. |
| `events.module` | `events` | The per-asset event runtime behind `ref.events`. |
| `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. |
| `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. |
| `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.assetType.shared")
rt.ref.loadTypeBehavior("material")
```
Fields resolve lazily. The prelude requires the sub-modules directly, in
dependency order (`ref`, then `changeDispatch`, `onRegister.install()`,
`refShapes.install()`) — a table that required all six on load would take that
ordering away from it.