Melon Sandbox: Lua Chip Programming Reference
Contents
- 1 Introduction
- 2 Execution Model and Lifecycle
- 3 Language Conventions
- 4 Typed Inputs and Outputs
- 5 Entity API
- 6 env Module
- 7 camera Module
- 8 input Module
- 9 spawn Module
- 10 chip Module
- 11 mechanic Module
- 12 uicontrol Module
- 13 world Module
- 14 variables Module
- 15 shared Table
- 16 signal Module
- 17 Custom Modules
- 18 Diagnostics
- 19 Standard Library
- 20 Programming Patterns
- 21 Complete Example
- 22 Appendix A: Function Index
- 23 Appendix B: Compatibility Notes
- 24 Appendix C: Unsupported API Names
1 Introduction
1.1 Purpose
This reference describes the Lua scripting interface exposed by the Lua Chip mechanic in Melon Sandbox. It covers script execution, typed pins, entity operations, built-in modules, inter-chip communication and practical patterns. Behavior that is not specified in the reference is identified as such rather than assumed.
1.2 Scope
The Lua Chip is a mechanic that runs a user-supplied Lua script. The script reads typed input pins, writes typed output pins, manipulates game entities, and communicates with other chips. The API is organized into the following namespaces:
| Namespace | Role |
|---|---|
Entity(id) | Object wrapper: transform, physics, health, visuals, events |
entity | Static entity functions (count, search) |
env | Time, session, date, map |
camera | Camera position, zoom, following |
input | Pointer, multi-touch, gestures, keyboard |
spawn | Catalogs and creation of objects, saves, mods |
chip | Introspection and I/O of other VPChip / LuaChip mechanics |
mechanic | Introspection and I/O of standard (non-chip) mechanics |
uicontrol | Runtime access to UIControl panels |
world | Session, persistence, cleanup, radio |
variables | Chip-level and global persistent variables |
shared | Table shared between all chips |
signal | Event bus between chips |
register_module, require | Code sharing between chips |
print, warn, error_log | Diagnostics |
inputs, outputs | Typed pins |
1.3 Notation
- Signatures are written as
name(parameter, ...). Optional parameters are marked[parameter]. ->denotes a return value. Multiple return values are separated by commas.- Methods invoked on an entity use the colon form
e:method(); module functions use the dot formmodule.function(). - Pin names and local identifiers in examples are lowercase. Code examples contain no comments; explanations are given in the surrounding text.
1.4 Accuracy and Version Compatibility
The available API and edge-case behavior may differ between game versions. This reference records the interface and behavior described by the material used to prepare it; it does not claim that every function has been independently tested in every release. When a behavior is marked as unspecified, do not depend on an assumed result. Verify version-sensitive behavior in the current game build before using it in a critical script.
1.5 Basic Workflow
- Write the required input and output references in the script so the corresponding typed pins can be exposed by the Lua Chip.
- Connect compatible output and input gates in the in-game editor. Use the pin family that matches the value being transferred.
- Read inputs inside OnTick or an appropriate callback. Supply defaults for unconnected scalar inputs.
- Validate entity IDs before calling entity methods. For UIControl, validate the panel entity with uicontrol.hasUIControl.
- Write output values during each tick in which they are needed. Use callbacks for deferred spawning and event subscriptions for collision or trigger events.
2 Execution Model and Lifecycle
2.1 Script Structure
A script is a Lua chunk. Code placed outside any function executes once, at the first compilation. The function OnTick is mandatory. All other callbacks are optional.
2.2 Callbacks
| Callback | Required | Invocation |
|---|---|---|
| (top-level code) | n/a | Once, at first compilation |
OnInit() | No | Once, after the first execution of the chunk and before the first OnTick |
OnTick() | Yes | Every tick |
OnActivated() | No | When the chip is activated |
OnDeactivated() | No | When the chip is deactivated |
OnSpawned(request_id, entities) | No | When a deferred spawn request completes |
OnDestroy() | No | When the chip is destroyed |
2.3 Ordering Guarantees
- Entity collision, trigger and wire subscription callbacks are invoked before
OnTick, in a pre-execute hook. - Signals sent with
signal.deferare delivered at the beginning of the next tick. - Spawn requests are deferred; their results arrive in
OnSpawned, not at the call site.
2.4 State Persistence
| Storage | Scope | Survives recompilation / scene reload | Written to disk |
|---|---|---|---|
Script-level local variables | Single chip | No | No |
variables.Set / variables.Get | Single chip | Conditional (see Section 14) | Conditional |
variables.SetGlobal / variables.GetGlobal | All chips | Not specified | Not specified |
shared table | All chips | Only via shared.Save() | Only via shared.Save() |
Script-level locals live in the closure of the chunk and are isolated per chip. They are reset when the script is recompiled or when the scene is reloaded.
2.5 Minimal Script
local tick = 0
function OnInit()
end
function OnTick()
tick = tick + 1
outputs.num.tick = tick
end
function OnActivated()
end
function OnDeactivated()
end
function OnSpawned(request_id, entities)
end
function OnDestroy()
end2.6 Error Reporting
The engine reports script errors automatically to the console:
[compile] ERROR: ...
[runtime] ERROR in OnTick: ...2.7 Activation Callbacks
OnActivated and OnDeactivated are invoked on activation transitions of the chip. Input pins may be read inside OnActivated; a script can, for example, read inputs.* there and perform one spawn per activation.
3 Language Conventions
3.1 Boolean Values
Many status and success functions return numeric values: 1 for true or success and 0 for false or failure. Do not assume that every API member uses this convention; fields and other functions may return Lua booleans, nil, strings or numbers as documented in their signatures. For example, compare e:isValid() == 1.
3.2 Nil Results
Some functions return nil when the requested item does not exist (for example e:getParent(), entity.find(name), chip.getValue(id, name) for an unknown gate). The same guard is advisable for e:getName(), e:getLocalizedName() and e:getPhysicMaterial(). Defensive forms are idiomatic:
local name = e:getName() or "?"
local parent_id = e:getParent() or 03.3 Multiple Return Values
Position-like and size-like functions return several values:
local px, py = e:getPosition()
local r, g, b, a = e:getColor()3.4 Indexing
Arrays are sequential Lua tables, indexed from 1. Touch indices (input.touch*) are also 1-based.
3.5 Units
| Quantity | Unit |
|---|---|
| Angles | Degrees |
| Angular velocity | Degrees per second |
| Time | Seconds |
| World coordinates | World units |
| Screen coordinates | Pixels |
| Color components | 0..1 |
Anchors (uicontrol) | 0..1 |
3.6 Descriptor Strings
Introspection functions return arrays of strings with a | separator:
| Source | Format |
|---|---|
chip.getInputs, chip.getOutputs | key|GateDataType |
mechanic.getInputs, mechanic.getOutputs | key|GateDataType |
uicontrol.getElements | name|type|id |
uicontrol.getInputGates, uicontrol.getOutputGates | name|type |
spawn.getItems | name|alias |
spawn.getSaves, spawn.getResourceSaves, spawn.getMods | name|id (see Appendix B) |
Fields are extracted with patterns such as entry:match("^([^|]+)") (first field) and entry:match("|([^|]+)$") (last field).
3.7 Call Syntax
Entity methods require the colon operator (e:getPosition()). Module functions use the dot operator (env.time()).
4 Typed Inputs and Outputs
4.1 Type Families
Pins are accessed through the global tables inputs and outputs. Each is divided into type families:
| Family | Lua representation | Notes |
|---|---|---|
num | number (double) | Floating-point |
int | number (integer) | Integer |
string | string | |
vec | table {x, y, z, w} | Four components |
color | table {r, g, b, a} | Components 0..1 |
entity | number | instanceID; wrap with Entity() |
array_num | table of numbers | 1-indexed |
array_string | table of strings | 1-indexed |
array_vec | table of {x, y, z, w} | 1-indexed |
array_entity | table of instanceIDs | 1-indexed |
Access form: inputs.<family>.<pin_name> and outputs.<family>.<pin_name>.
4.2 Rules
- Sub-tables always exist.
inputs.num,inputs.vec, and so on are nevernil; access is nil-safe at the family level. - Unconnected inputs are
nil(scalar types). Supply defaults withor. - Array inputs default to an empty table when written as
inputs.array_num.values or {}. - Pin discovery. The Lua Chip editor derives pin definitions from references in the script. Reference every input and output pin that you intend to use.
- Output values. Assign each output during every tick in which its value must be maintained. An output not assigned during a tick returns to its default; numeric outputs default to 0 and string outputs to an empty string.
- Unused vector components are set to
0. - Entity pins carry an instanceID. A missing entity is
nilor0.
4.3 Scalar Example
function OnTick()
local speed = inputs.num.speed or 0
local count = inputs.int.count or 0
local label = inputs.string.label or ""
local direction = inputs.vec.direction
local tint = inputs.color.tint
local target_id = inputs.entity.target or 0
local dx = direction and direction.x or 0
local dy = direction and direction.y or 0
local red = tint and tint.r or 1
outputs.num.tick = (outputs.num.tick or 0) + 1
outputs.int.counter = count + 1
outputs.string.status = "ok " .. label
outputs.vec.heading = { x = dx, y = dy, z = 0, w = 0 }
outputs.color.glow = { r = red, g = 1, b = 0, a = 1 }
outputs.entity.found = target_id
end4.4 Array Example
function OnTick()
local numbers = inputs.array_num.values or {}
local tags = inputs.array_string.tags or {}
local points = inputs.array_vec.points or {}
local targets = inputs.array_entity.targets or {}
for index = 1, #numbers do
local value = numbers[index]
end
outputs.array_num.filtered = { 1, 2, 3 }
outputs.array_string.labels = { "first", "second" }
outputs.array_vec.path = {
{ x = 0, y = 0, z = 0, w = 0 },
{ x = 1, y = 2, z = 0, w = 0 }
}
outputs.array_entity.captured = { 101, 102 }
end4.5 Float-Valued Action Pins
A numeric pin (inputs.num.action) is commonly used as a command selector. Test integer ranges rather than equality, so that the selector tolerates fractional values:
local action = inputs.num.action or 0
if action >= 1 and action < 2 then
elseif action >= 2 and action < 3 then
elseif action >= 3 then
end4.6 Pin Connection Workflow
A pin is declared by using its typed path in the script. For example, inputs.entity.target declares an entity input named target, while outputs.num.speed declares a numeric output named speed. The name after the type family is the pin name. Connect an output gate to an input gate of a compatible type in the in-game editor.
function OnTick()
local target_id = inputs.entity.target or 0
local speed = inputs.num.speed or 0
outputs.num.current_speed = speed
outputs.entity.current_target = target_id
endAn entity pin carries an entity instanceID, not an Entity object. Wrap the ID with Entity(id) before calling entity methods. If a pin is unconnected, its value may be nil; use a default and validate the resulting entity.
5 Entity API
5.1 Construction and Validity
Entity(id) wraps an instanceID in an entity object. All entity methods are invoked on this object. An entity object whose target does not exist is a nil entity, detectable by the field _nil.
| Member | Parameters | Returns | Description |
|---|---|---|---|
Entity(id) | id: instanceID | entity object | Wraps an instanceID |
e._nil | none (field) | boolean-like | Truthy when the entity is absent; always test before use |
e:getId() | none | number | instanceID |
e:isValid() | none | 1/0 | 1 if the object is alive |
function OnTick()
local e = Entity(inputs.entity.target)
if e._nil then
outputs.string.status = "no entity"
return
end
if e:isValid() == 1 then
outputs.num.id = e:getId()
end
endEntities captured in long-lived structures can be destroyed in the meantime. Validate with isValid() before use, for example in OnDestroy.
5.2 Transform
| Method | Parameters | Returns | Description |
|---|---|---|---|
getPosition() | none | x, y | World position |
setPosition(x, y) | x, y | none | Set world position |
getAngle() | none | degrees | World angle |
setAngle(angle) | degrees | none | Set world angle |
getScale() | none | scale_x, scale_y | Scale |
setScale(x, y) | x, y | none | Set scale |
getNormal() | none | x, y | Up vector of the object |
localToWorld(x, y) | local x, y | world x, y | Coordinate conversion |
worldToLocal(x, y) | world x, y | local x, y | Coordinate conversion |
localAngleToWorld(angle) | degrees | degrees | Angle conversion |
worldAngleToLocal(angle) | degrees | degrees | Angle conversion |
5.3 Physics
| Method | Parameters | Returns | Description |
|---|---|---|---|
getVelocity() | none | vx, vy | Linear velocity |
setVelocity(vx, vy) | vx, vy | none | Set linear velocity |
getAngularVelocity() | none | degrees/s | Angular velocity |
setAngularVelocity(omega) | degrees/s | none | Set angular velocity |
addForce(fx, fy) | fx, fy | none | Apply a force (world) |
addTorque(torque) | torque | none | Apply torque |
addForceAtPosition(fx, fy, px, py) | force, world point | none | Apply a force at a point |
getVelocityAtPoint(x, y) | world point | vx, vy | Velocity at a world point |
getMass() | none | number | Mass |
getCenterOfMass() | none | x, y | Center of mass (world) |
getGravityScale() | none | number | Gravity multiplier |
setGravityScale(scale) | scale | none | 0 disables gravity, 1 restores it |
freeze(flag) | 1/0 | none | 1 static body, 0 dynamic body |
freezeRotation(flag) | 1/0 | none | 1 forbids rotation, 0 allows it |
setCollisionEnabled(flag) | 1/0 | none | 0 moves the object to the NoCollide layer, 1 restores the layer |
Forces are typically applied every tick for a sustained effect:
function OnTick()
local e = Entity(inputs.entity.target)
if e._nil then return end
e:addForce(0, 500)
end5.4 Health and Temperature
| Method | Parameters | Returns | Description |
|---|---|---|---|
getTemperature() | none | number | Temperature |
setTemperature(value) | number | none | Set temperature |
isOnFire() | none | 1/0 | Burning state |
isFrozen() | none | 1/0 | Frozen state |
ignite() | none | none | Set on fire |
extinguish() | none | none | Extinguish |
getHealth() | none | number | Health |
isBreakable() | none | 1/0 | Whether the object can be broken |
Guard these getters with or 0: a result may be nil for objects lacking the component.
5.5 Visuals
| Method | Parameters | Returns | Description |
|---|---|---|---|
getColor() | none | r, g, b, a | Color, each 0..1 |
setColor(r, g, b, [a]) | r, g, b, optional a | none | Alpha defaults to 1 |
getName() | none | string | Internal ObjectName |
getLocalizedName() | none | string | Localized name |
isVisible() | none | 1/0 | Visibility (InvisibleComponent); 0 = hidden |
setVisible(flag) | 1/0 | none | Hide (0) or show (1) |
function OnTick()
local e = Entity(inputs.entity.target)
if e._nil or e:isValid() ~= 1 then return end
e:setColor(0, 1, 0, 1)
end5.6 Electricity
| Method | Parameters | Returns | Description |
|---|---|---|---|
getVoltage() | none | number | Voltage |
5.7 Interaction
| Method | Parameters | Returns | Description |
|---|---|---|---|
isDraggable() | none | 1/0 | Whether the object can be dragged |
setDraggable(flag) | 1/0 | none | Forbid (0) or allow (1) dragging |
activate(flag) | 1/0 | none | Activate (1) or deactivate (0) the object’s mechanic |
getActivationInput() | none | number | Current activation value |
delete() | none | none | Destroy the object |
5.8 Identity and Static Functions
| Function | Parameters | Returns | Description |
|---|---|---|---|
e:getId() | none | number | instanceID |
e:isValid() | none | 1/0 | Liveness |
entity.all() | none | number | Number of objects in the scene |
entity.find(name) | string | number or nil | instanceID of the first object with this name |
Note: the namespace entity (lowercase, static functions) is distinct from the constructor Entity (capitalized).
5.9 Hierarchy
| Method | Parameters | Returns | Description |
|---|---|---|---|
getRoot() | none | instanceID | Topmost object with Properties in the hierarchy; the object’s own id if it is already the root |
getParent() | none | instanceID or nil | Nearest parent with Properties |
getChildren() | none | array of instanceIDs | Direct children only (one level); may be empty |
function OnTick()
local e = Entity(inputs.entity.target)
if e._nil then return end
local root_id = e:getRoot()
local parent_id = e:getParent()
local children = e:getChildren()
for index = 1, #children do
local child = Entity(children[index])
if not child._nil then
outputs.string.last_child = child:getName()
end
end
end5.10 Bounds
| Method | Parameters | Returns | Description |
|---|---|---|---|
getSize() | none | width, height | Actual size = base size multiplied by scale; cached; independent of rotation |
getBaseSize() | none | width, height | Size at scale 1 |
getBounds() | none | center_x, center_y, width, height | World AABB of the first renderer; depends on rotation |
getFullBounds() | none | center_x, center_y, width, height | World AABB of all renderers |
getColliderBounds() | none | center_x, center_y, width, height | World AABB of the collider |
5.11 Extended Functions
| Method | Parameters | Returns | Description |
|---|---|---|---|
lookAt(target_id, speed) | instanceID, degrees/s | none | Rotate toward the target at the given angular speed |
getElevation(x, y) | world point | degrees | Angle from the entity to the point |
canBeActivated() | none | 1/0 | Whether the entity has a Mechanic |
getPhysicMaterial() | none | string | Physics material name |
lookAt is intended to be called every tick.
5.12 Collision and Trigger Subscriptions
Subscriptions register callbacks for physical events of one entity. Each subscribe* function returns a numeric subscription id used for unsubscription. Callbacks execute before OnTick.
| Method | Callback signature | Description |
|---|---|---|
subscribeCollisionEnter(fn) | fn(other, self, nx, ny) | Collision begins; nx, ny is the collision normal |
subscribeCollisionExit(fn) | fn(other, self) | Collision ends |
subscribeCollisionStay(fn) | fn(other, self) | Every tick while objects touch |
subscribeTriggerEnter(fn) | fn(other, self) | Entry into a trigger zone |
subscribeTriggerExit(fn) | fn(other, self) | Exit from a trigger zone |
subscribeTriggerStay(fn) | fn(other, self) | Every tick while inside a trigger zone |
In callbacks, other is the entity object of the counterpart and self is the entity object that owns the subscription. Triggers have no normal.
| Unsubscription | Parameters |
|---|---|
unsubscribeCollisionEnter(sub_id) | id returned by the matching subscribe |
unsubscribeCollisionExit(sub_id) | id |
unsubscribeCollisionStay(sub_id) | id |
unsubscribeTriggerEnter(sub_id) | id |
unsubscribeTriggerExit(sub_id) | id |
unsubscribeTriggerStay(sub_id) | id |
unsubscribeAll() | removes all subscriptions of the entity |
local sub_id = nil
function OnTick()
local e = Entity(inputs.entity.target)
if e._nil then return end
if not sub_id then
sub_id = e:subscribeCollisionEnter(function(other, self, nx, ny)
if other._nil then return end
print("hit " .. other:getName())
end)
end
end
function OnDestroy()
local e = Entity(inputs.entity.target)
if not e._nil and e:isValid() == 1 then
e:unsubscribeAll()
end
endSubscribe once; subscribing on every tick creates duplicate callbacks. Test other._nil before use.
5.13 Wire Subscriptions
Wire subscriptions fire when a wire is connected to or disconnected from a gate of a chip.
| Method | Callback signature | Description |
|---|---|---|
subscribeWireConnected(fn) | fn(self_id, input_key, output_entity_id, output_key) | A wire was connected. self_id: chip that received the wire; input_key: gate on this chip; output_entity_id: chip at the other end; output_key: gate on that chip |
subscribeWireDisconnected(fn) | fn(self_id, input_key) | A wire was disconnected |
unsubscribeWireConnected(sub_id) | id | Remove the subscription |
unsubscribeWireDisconnected(sub_id) | id | Remove the subscription |
6 env Module
Environment, time, session and map information.
| Function | Returns | Description |
|---|---|---|
env.time() | seconds | Scaled game time (Time.time) |
env.deltaTime() | seconds | Frame delta (Time.deltaTime) |
env.fixedDeltaTime() | seconds | Fixed physics step (Time.fixedDeltaTime) |
env.timeScale() | number | Current time scale |
env.setTimeScale(scale) | none | Set time scale; documented range 0..2 |
env.frameCount() | number | Frame number |
env.sessionTime() | seconds | Time since the session started |
env.entityCount() | number | Number of objects in the scene |
env.isWorld() | 1/0 | Whether the context is a world |
env.isWorldEditor() | 1/0 | Whether the context is the world editor |
env.systemTime() | seconds | UTC seconds since the epoch |
env.systemDate() | days | UTC days since the epoch |
env.toDate(days) | string | Formats days as dd.MM.yyyy |
env.toTimeFormat(seconds) | string | Formats seconds as HH:MM:SS |
env.parseDate(text) | days | Parses dd.MM.yyyy into days since the epoch; 0 on failure |
env.getMapSize() | x, y | Map size; -1, -1 if the map is infinite |
function OnTick()
outputs.num.time = env.time()
outputs.string.date = env.toDate(env.systemDate())
outputs.string.session = env.toTimeFormat(env.sessionTime())
local map_x, map_y = env.getMapSize()
outputs.vec.map_size = { x = map_x, y = map_y, z = 0, w = 0 }
end7 camera Module
| Function | Parameters | Returns | Description |
|---|---|---|---|
camera.getPosition() | none | x, y | Camera position |
camera.setPosition(x, y) | x, y | none | Set position; ignored while following |
camera.getZoom() | none | number | Zoom value |
camera.setZoom(value) | number | none | Set zoom value |
camera.follow(entity_id) | instanceID | none | Follow an entity |
camera.unfollow() | none | none | Stop following |
camera.isFollowing() | none | 1/0 | Following state |
camera.setPosition(x, y) is ignored while camera.follow is active. Call camera.unfollow() before controlling the camera position directly. A lower zoom value zooms in; a higher value zooms out.
function OnTick()
local target = Entity(inputs.entity.follow_target)
if not target._nil and target:isValid() == 1 then
camera.follow(target:getId())
else
camera.unfollow()
end
end8 input Module
Mouse and touch are unified: one API serves desktop (the mouse counts as one finger) and mobile. All boolean-like results are 1/0.
8.1 Pointer
The pointer is the primary finger or the mouse.
| Function | Returns | Description |
|---|---|---|
input.pointerDown() | 1/0 | Pointer pressed |
input.pointerUp() | 1/0 | Pointer released in this frame |
input.pointerPos() | x, y | World coordinates |
input.pointerScreenPos() | x, y | Screen pixels |
input.pointerDelta() | dx, dy | Movement delta per frame (pixels) |
8.2 Raycast
| Function | Returns | Description |
|---|---|---|
input.pointerRaycast() | instanceID | First object under the pointer; 0 if none |
input.pointerRaycastAll() | array of instanceIDs | All objects under the pointer; unique |
function OnTick()
local hit_id = input.pointerRaycast()
if hit_id ~= 0 then
outputs.entity.clicked = hit_id
end
local hits = input.pointerRaycastAll()
for index = 1, #hits do
local hit = Entity(hits[index])
if not hit._nil then
print("hit: " .. hit:getName())
end
end
end8.3 UI Filtering
| Function | Returns | Description |
|---|---|---|
input.isOverUI() | 1/0 | Pointer is over UI |
input.pointerDownFiltered() | 1/0 | Pressed, and the press did not start over UI |
input.pointerUpFiltered() | 1/0 | Released, and the press did not start over UI |
8.4 Multi-Touch
Touch functions take a 1-based finger index i. The index is the position in the finger list and is stable within a frame. For tracking between frames use input.touchId(i), a stable hardware id. Query input.touchCount() before indexing.
| Function | Returns | Description |
|---|---|---|
input.touchCount() | number | Number of active fingers |
input.touchSet(i) | 1/0 | Finger is touching now |
input.touchDown(i) | 1/0 | Pressed in this frame |
input.touchUp(i) | 1/0 | Released in this frame |
input.touchAge(i) | seconds | Time since the touch began |
input.touchId(i) | number | Stable hardware id |
input.touchPos(i) | x, y | World coordinates |
input.touchScreenPos(i) | x, y | Current screen pixels |
input.touchStartScreenPos(i) | x, y | Screen position at touch start |
input.touchDelta(i) | dx, dy | Delta per frame |
input.touchSwipeDelta(i) | dx, dy | Total displacement since touch start |
input.touchTap(i) | 1/0 | 1 only in the frame of a tap event |
input.touchTapCount(i) | number | Consecutive taps (double tap = 2) |
input.touchSwipe(i) | 1/0 | 1 only in the frame of a swipe event |
input.touchIsOverUI(i) | 1/0 | Currently over UI |
input.touchStartedOverUI(i) | 1/0 | Started over UI (sticky for the whole touch) |
8.5 Gestures
Two-finger helpers operate on fingers 1 and 2 by default. Explicit indices may be passed, for example input.pinchDistance(2, 3).
| Function | Returns | Description |
|---|---|---|
input.pinchDistance([a, b]) | pixels | Distance between the fingers; 0 if fewer than two |
input.pinchAngle([a, b]) | degrees | Angle from finger a to finger b (rotation gesture) |
input.pinchCenter([a, b]) | x, y | Center between the fingers in screen space |
Pinch-zoom is implemented by tracking the change of distance between ticks (positive change = fingers moving apart):
local last_distance = nil
function OnTick()
if input.touchCount() >= 2 then
local distance = input.pinchDistance()
if last_distance then
outputs.num.pinch_delta = distance - last_distance
end
last_distance = distance
else
last_distance = nil
outputs.num.pinch_delta = 0
end
end8.6 Keyboard
| Function | Returns | Description |
|---|---|---|
input.key(name) | 1/0 | Key is held |
input.keyDown(name) | 1/0 | Key pressed in this frame |
Documented key names (lowercase strings): "a" to "z", "0" to "9", "space", "left", "right", "up", "down", "left shift", "right shift", "left ctrl", "return", "escape", "tab", "backspace".
function OnTick()
local e = Entity(inputs.entity.target)
if e._nil then return end
if input.key("space") == 1 then
e:addForce(0, 50)
end
end9 spawn Module
The spawn module exposes catalogs of spawnable content and creates objects. Creation is deferred: functions return a request id immediately, and the created entities are delivered to OnSpawned (Section 9.7).
9.1 Catalogs
| Function | Returns | Entry format |
|---|---|---|
spawn.getItems() | array of strings | name|alias |
spawn.getItemsString([separator]) | string | Joined entries; default separator ", " |
spawn.getItemCount() | number | Count |
spawn.getSaves() | array of strings | User saves |
spawn.getSavesString([separator]) | string | Joined entries |
spawn.getSaveCount() | number | Count |
spawn.getResourceSaves() | array of strings | Built-in saves from resources |
spawn.getResourceSavesString([separator]) | string | Joined entries |
spawn.getResourceSaveCount() | number | Count |
spawn.getMods() | array of strings | Mods |
spawn.getModsString([separator]) | string | Joined entries |
spawn.getModCount() | number | Count |
Entries of the form name|key are split with entry:match("^([^|]+)") to obtain the name.
9.2 Object Creation
| Function | Parameters | Returns | Description |
|---|---|---|---|
spawn.create(alias, x, y) | alias string, world x, y | request id | Create a standard object |
spawn.createWithAngle(alias, x, y, angle) | alias, x, y, degrees | request id | Create with a rotation |
9.3 Cloning
| Function | Parameters | Returns | Description |
|---|---|---|---|
spawn.clone(entity_id, x, y) | instanceID, x, y | request id | Clone (persisted) |
spawn.cloneTemp(entity_id, x, y) | instanceID, x, y | request id | Temporary clone (not persisted) |
9.4 Saves and Mods
| Function | Parameters | Returns | Description |
|---|---|---|---|
spawn.createSave(name, x, y) | save name, x, y | request id | Spawn a save; OnSpawned receives all of its entities |
spawn.createMod(name, x, y) | mod name, x, y | request id | Spawn a mod; OnSpawned receives all of its entities |
9.5 Destruction
| Function | Parameters | Returns | Description |
|---|---|---|---|
spawn.destroy(entity_id) | instanceID | none | Immediate removal |
9.6 Alias Lookup
| Function | Parameters | Returns | Description |
|---|---|---|---|
spawn.getNameByAlias(alias) | alias | string | Localized name; empty or nil for an unknown alias |
spawn.existsByAlias(alias) | alias | 1/0 | Whether the alias exists |
9.7 The OnSpawned Callback
OnSpawned(request_id, entities)| Parameter | Description |
|---|---|
request_id | The number returned by the originating spawn.* call |
entities | Array of entity objects (always an array, even for one object); nil on error |
local pending = {}
local spawned_ids = {}
function OnActivated()
local alias = tostring(inputs.string.object_alias or "")
if alias == "" then return end
local x = inputs.num.x or 0
local y = inputs.num.y or 5
local request_id = spawn.create(alias, x, y)
pending[request_id] = true
end
function OnSpawned(request_id, entities)
pending[request_id] = nil
if not entities then
print("spawn failed, request " .. request_id)
return
end
for index = 1, #entities do
spawned_ids[#spawned_ids + 1] = entities[index]:getId()
end
end
function OnTick()
outputs.num.alive_count = #spawned_ids
end10 chip Module
Introspection and gate access for VPChip and LuaChip mechanics. For UIControl panels use uicontrol; for other mechanics use mechanic.
| Function | Parameters | Returns | Description |
|---|---|---|---|
chip.has(id) | instanceID | 1/0 | Whether the entity is a chip |
chip.getType(id) | instanceID | "VPChip", "LuaChip" or nil | Chip kind |
chip.getInputs(id) | instanceID | array of key|GateDataType or nil | Input gates |
chip.getOutputs(id) | instanceID | array of key|GateDataType or nil | Output gates |
chip.getValue(id, gate) | id, gate name | value or nil | Reads a gate; outputs are searched first, then inputs |
chip.setValue(id, gate, value) | id, gate name, value | 1/0 | Writes a gate; 0 if the gate is connected by a wire |
chip.hasWire(id, gate) | id, gate name | 1/0 | Whether a wire is attached to the input gate |
chip.getActivation(id) | instanceID | number | Current ActivationInput |
chip.setActivation(id, value) | id, value | 1/0 | Writes ActivationInput |
chip.getName(id) | instanceID | string | Visual name or __name input |
chip.getTPS(id) | instanceID | number | Ticks per second |
Edge-case behavior: chip.has(0) returns 0; chip.getType(0) returns nil; chip.getValue(id, "unknown_gate") returns nil.
Gate type names observed in descriptors: Number, IntegerNumber, String, Vector, Color, Entity.
function OnTick()
local id = inputs.entity.target or 0
if chip.has(id) == 0 then
outputs.string.status = "not a chip"
return
end
local inputs_list = chip.getInputs(id) or {}
if #inputs_list > 0 then
local gate = tostring(inputs_list[1]):match("^([^|]+)")
if chip.hasWire(id, gate) == 0 then
chip.setValue(id, gate, 42)
end
end
outputs.string.status = chip.getType(id)
end11 mechanic Module
Introspection and gate access for standard mechanics (guns, doors, thrusters, timers, motors, buttons). The module excludes VPChip, LuaChip and UIControlMechanic.
| Function | Parameters | Returns | Description |
|---|---|---|---|
mechanic.has(id) | instanceID | 1/0 | Whether the entity has a standard mechanic |
mechanic.getType(id) | instanceID | string or nil | Mechanic class name |
mechanic.getInputs(id) | instanceID | array of key|type or nil | Input gates |
mechanic.getOutputs(id) | instanceID | array of key|type or nil | Output gates |
mechanic.getValue(id, gate) | id, gate name | value or nil | Reads a gate |
mechanic.setValue(id, gate, value) | id, gate name, value | 1/0 | Writes a gate; 0 if wired or unknown |
mechanic.hasWire(id, gate) | id, gate name | 1/0 | Wire attached |
mechanic.getActivation(id) | instanceID | number | ActivationInput |
mechanic.setActivation(id, value) | id, value | 1/0 | Writes ActivationInput |
Value types accepted by setValue, chosen according to the gate type in the descriptor:
| Gate type | Value |
|---|---|
Number, IntegerNumber | number |
String | string |
Vector, Color | table {x = 1, y = 0, z = 0, w = 1} |
Edge cases: mechanic.has(0) returns 0; mechanic.getType(0) returns nil; getValue for an unknown gate returns nil; setValue for an unknown or wired gate returns 0; hasWire for an unknown gate returns 0.
function OnTick()
local id = inputs.entity.target or 0
if mechanic.has(id) == 0 then return end
local gates = mechanic.getInputs(id) or {}
for index = 1, #gates do
local entry = tostring(gates[index])
local gate = entry:match("^([^|]+)")
local kind = entry:match("|(.+)$")
if mechanic.hasWire(id, gate) == 0 and kind == "Number" then
mechanic.setValue(id, gate, 0.5)
break
end
end
end12 uicontrol Module
Runtime access to UIControl panels. The panel is the entity that carries the UIControlMechanic. The panel instanceID and an individual UI element ID are different values.
- Id: a runtime element id used for reading and writing its gates;
- Name: a user-defined name, resolvable with
findElement; - Type: for example
Button,Label,Slider,Joystick.
Gate names depend on the element type (examples: "Button is down", "Label Text").
Pass the panel entity's instanceID as panel. Do not pass an element ID to hasUIControl, getElements or findElement. Check uicontrol.hasUIControl(panel) == 1 before querying elements. Use uicontrol.getElements(panel) to inspect the available names, types and IDs, then use the exact gate names returned by the element's gate lists.
In the signatures panel is the instanceID of the entity carrying the UIControlMechanic and element_id is an element Id.
| Function | Returns | Description |
|---|---|---|
uicontrol.hasUIControl(panel) | 1/0 | Whether the entity has a UIControl |
uicontrol.getElements(panel) | array of name|type|id or nil | All elements |
uicontrol.findElement(panel, name) | element id | Element lookup by name |
uicontrol.getElementsByType(panel, type_name) | array of element ids | Elements of a type |
uicontrol.getInputGates(panel, element_id) | array of name|type or nil | Input gates of an element |
uicontrol.getOutputGates(panel, element_id) | array of name|type or nil | Output gates of an element |
uicontrol.getValue(panel, element_id, gate) | value or nil | Reads a gate |
uicontrol.setValue(panel, element_id, gate, value) | 1/0 | Writes a gate; 0 if wired or unknown |
uicontrol.hasWire(panel, element_id, gate) | 1/0 | Wire attached to the gate |
uicontrol.getAnchors(panel, element_id) | min_x, min_y, max_x, max_y | RectTransform anchors, 0..1 |
uicontrol.getAnchoredPosition(panel, element_id) | x, y | Anchored position |
uicontrol.setAnchoredPosition(panel, element_id, x, y) | none | Move the element at runtime |
Element descriptors have the form name|type|id; the id is the third field:
function OnTick()
local panel = inputs.entity.panel or 0
if uicontrol.hasUIControl(panel) ~= 1 then
outputs.string.status = "invalid panel"
outputs.num.pressed = 0
return
end
local button_id = uicontrol.findElement(panel, "play_btn")
if not button_id or button_id == 0 then
outputs.string.status = "button not found"
outputs.num.pressed = 0
return
end
local pressed = uicontrol.getValue(panel, button_id, "Button is down")
outputs.num.pressed = pressed or 0
outputs.string.status = "ok"
endEdge cases: getValue, setValue and hasWire on a nonexistent element return nil, 0, 0 respectively; hasUIControl(0) returns 0; getElements(0) returns nil.
Example element type names: Button, Label, Slider1, Joystick, Toggle1, Indicator1.
function OnTick()
local panel = inputs.entity.target or 0
if uicontrol.hasUIControl(panel) == 0 then return end
local button_id = uicontrol.findElement(panel, "play_btn")
local pressed = uicontrol.getValue(panel, button_id, "Button is down")
outputs.num.pressed = pressed or 0
local label_id = uicontrol.findElement(panel, "status_label")
uicontrol.setValue(panel, label_id, "Label Text", "Hello")
end13 world Module
| Function | Returns | Description |
|---|---|---|
world.isSessionActive() | 1/0 | Whether a session is active |
world.startSession() | none | Start a session |
world.endSession() | none | End the session |
world.save() | none | Save the current state |
world.load() | none | Load the last save |
world.reset() | none | Reset to the initial state |
world.clearCorpses() | none | Remove corpses |
world.clearDecals() | none | Remove decals (blood, traces) |
world.clearGibs() | none | Remove debris |
world.clearLiving() | none | Remove living beings |
world.radioSignal(channel) | number | Signal value on a radio channel |
14 variables Module
Named values stored through the gate-data system.
| Function | Parameters | Returns | Description |
|---|---|---|---|
variables.Set(name, value) | string, value | ok, error | ok is 1 on success; on failure 0 and an error message |
variables.Get(name) | string | value or nil | Chip-level read |
variables.SetGlobal(name, value) | string, value | ok, error | Global write |
variables.GetGlobal(name) | string | value or nil | Global read |
Characteristics:
- Chip-level variables are held in the VariablesGateDataComponent of the owning chip.
- The type of a variable is fixed at creation: a Number remains a Number.
- Persistence between sessions is controlled by the “save between session” flag on the variable in the chip editor. The flag is visible only in WorldEditor.
- For data exchange between chips use
shared,signalorregister_modulerather than variables.
function OnTick()
local total = (variables.Get("total_ticks") or 0) + 1
local ok, err = variables.Set("total_ticks", total)
if ok ~= 1 then
error_log("variables.Set failed: " .. tostring(err))
end
outputs.num.total_ticks = total
variables.SetGlobal("score", 100)
outputs.num.score = variables.GetGlobal("score") or 0
end15 shared Table
shared is a table visible to every chip. It holds values of any Lua type, including nested tables.
| Operation | Description |
|---|---|
shared.key = value | Write |
shared.key | Read; nil if absent |
shared.Save() | Serialize to GlobalVariables (in worlds) |
shared.Load() | Load from GlobalVariables (in worlds) |
function OnInit()
shared.player = { hp = 100, items = {} }
shared.messages = shared.messages or {}
end
function OnTick()
shared.score = (shared.score or 0) + 1
table.insert(shared.player.items, "sword")
end15.1 Message Queue Convention
A queue can be implemented as an array in shared.messages. The producer appends records; the consumer keeps a private cursor and processes only new entries (Section 20.6).
15.2 Caveats
sharedis global: choose key names that avoid collisions between independent scripts.- Always guard against absence: the other chip may not have run yet (
if not shared.producer then return end). shared.Save()andshared.Load()persist through GlobalVariables in worlds; see Appendix B.
16 signal Module
An event bus between chips. Payloads may be any Lua value.
| Function | Parameters | Returns | Description |
|---|---|---|---|
signal.on(name, fn) | event name, fn(data) | subscription id | Subscribe. Call once, in OnInit or at top level |
signal.emit(name, data) | name, payload | none | Immediate delivery: all subscribers are called at once |
signal.defer(name, data) | name, payload | none | Delivery at the beginning of the next tick |
signal.off(name, sub_id) | name, id | none | Unsubscribe |
local last_damage = 0
function OnInit()
signal.on("damage", function(data)
last_damage = data.amount
print("damage: " .. data.amount)
end)
end
function OnTick()
if input.keyDown("space") == 1 then
signal.emit("damage", { amount = 10, source = "fire" })
end
outputs.num.last_damage = last_damage
end17 Custom Modules
Chips share reusable code through a registry.
| Function | Parameters | Description |
|---|---|---|
register_module(name, table) | string, table | Publish a module; may contain functions, tables, numbers, any Lua value |
require(name) | string | Import a registered module; available to all chips after registration |
Modules are stored in _G.__modules and are visible to every chip. A consumer that may start before the registering chip should call require under pcall:
function OnInit()
register_module("math_utils", {
clamp = function(value, low, high)
return math.max(low, math.min(high, value))
end,
lerp = function(a, b, t)
return a + (b - a) * t
end,
distance = function(x1, y1, x2, y2)
return math.sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2)
end,
})
endfunction OnTick()
local ok, utils = pcall(require, "math_utils")
if not ok then
outputs.string.status = "waiting for module"
return
end
outputs.num.clamped = utils.clamp(150, 0, 100)
outputs.num.middle = utils.lerp(0, 10, 0.5)
outputs.num.length = utils.distance(0, 0, 3, 4)
end18 Diagnostics
Three global functions write to the Lua console and to the Unity debug log at different severity levels, which can be filtered in the console.
| Function | Level | Intended use |
|---|---|---|
print(...) | Info | Diagnostics and ordinary tracing; multiple arguments are separated by tabs |
warn(...) | Warning | Non-critical problem requiring attention |
error_log(...) | Error | A genuine defect or unrecoverable condition |
function OnTick()
print("x =", 42, "y =", 3.14)
if not inputs.entity.target then
warn("target is not connected")
end
if (inputs.num.action or 0) > 3 then
error_log("invalid value:", inputs.num.action, "(expected 0..3)")
end
endCompilation and runtime errors are logged by the engine itself (see Section 2.6).
To avoid flooding the console, log on state changes rather than every tick:
local last_hit_id = 0
function OnTick()
local hit_id = input.pointerRaycast()
if hit_id ~= 0 and hit_id ~= last_hit_id then
local hit = Entity(hit_id)
if not hit._nil then
print("raycast hit " .. hit:getName())
end
end
last_hit_id = hit_id
end19 Standard Library
The following standard-library members are documented for use in the Lua Chip environment:
| Library | Members |
|---|---|
math | abs, floor, ceil, sqrt, sin, cos, atan2, pi, max, min, random, huge |
string | len, sub, find, format, rep, upper, lower, byte, char, gmatch, match |
table | insert, remove, sort, concat, unpack |
coroutine | create, resume, yield, status |
| base | pairs, ipairs, type, tostring, tonumber, select, unpack, pcall |
Libraries not listed (for example os and io) are not documented as available.
This list is intentionally limited to the members listed above. Do not assume that an unlisted Lua library or function is available. In particular, os and io are not documented as available.
20 Programming Patterns
20.1 Persistent State in Locals
local tick = 0
local first_tick = true
function OnTick()
tick = tick + 1
if first_tick then
first_tick = false
print("first tick")
end
outputs.num.tick = tick
end20.2 Command Selector With Change Detection
local last_action = 0
function OnTick()
local action = inputs.num.action or 0
local action_changed = math.floor(action) ~= math.floor(last_action)
last_action = action
if action >= 1 and action < 2 then
if action_changed then print("action 1") end
outputs.string.status = "action 1"
elseif action >= 2 and action < 3 then
if action_changed then print("action 2") end
outputs.string.status = "action 2"
else
outputs.string.status = "idle"
end
end20.3 Rising-Edge Toggle
local state = "running"
local was_trigger = 0
function OnTick()
local trigger = inputs.num.trigger or 0
if trigger >= 1 and was_trigger < 1 then
if state == "running" then
state = "paused"
else
state = "running"
end
end
was_trigger = trigger
outputs.string.state = state
if state ~= "running" then return end
end20.4 Subscribe Once
local subscribed = false
function OnTick()
local e = Entity(inputs.entity.target)
if e._nil then return end
if not subscribed then
subscribed = true
e:subscribeCollisionEnter(function(other, self, nx, ny)
if other._nil then return end
print("collision with " .. other:getName())
end)
end
end20.5 One-Shot Execution
local done = false
function OnTick()
if done then return end
local id = inputs.entity.target
if id == nil or id == 0 then
outputs.string.status = "waiting for entity"
return
end
done = true
print("running once for " .. tostring(id))
end20.6 Producer and Consumer Through shared
This pattern uses a bounded queue and one consumer. The consumer removes each message after processing it, so the queue does not grow indefinitely. If multiple consumers need every message, use separate queues or a different coordination design.
function OnTick()
local messages = shared.messages or {}
shared.messages = messages
if #messages >= 100 then
table.remove(messages, 1)
end
table.insert(messages, { from = "producer", type = "tick" })
endConsumer:
function OnTick()
local messages = shared.messages
if not messages or #messages == 0 then return end
local message = table.remove(messages, 1)
outputs.string.last_message = tostring(message.type)
outputs.num.message_count = (outputs.num.message_count or 0) + 1
end20.7 Distance Between Entities
function OnTick()
local a = Entity(inputs.entity.target)
local b = Entity(inputs.entity.other)
if a._nil or b._nil then return end
local ax, ay = a:getPosition()
local bx, by = b:getPosition()
outputs.num.distance = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2)
end20.8 Rate Limiting With env.time
local last_fire = 0
function OnTick()
local now = env.time()
if now - last_fire > 0.5 then
last_fire = now
print("fire")
end
end21 Complete Example
An automatic turret. Pins: entity target (turret), entity other (aim target), string bullet_alias. Outputs: number distance, string status.
local last_fire = 0
function OnInit()
print("turret initialized")
end
function OnTick()
local turret = Entity(inputs.entity.target)
local aim = Entity(inputs.entity.other)
if turret._nil or aim._nil then
outputs.string.status = "waiting"
return
end
turret:lookAt(aim:getId(), 180)
local now = env.time()
if now - last_fire > 0.5 then
last_fire = now
local bullet_alias = tostring(inputs.string.bullet_alias or "")
if bullet_alias ~= "" then
local px, py = turret:getPosition()
local nx, ny = turret:getNormal()
spawn.create(bullet_alias, px + nx * 2, py + ny * 2)
end
end
local tx, ty = aim:getPosition()
local px, py = turret:getPosition()
outputs.num.distance = math.sqrt((tx - px) ^ 2 + (ty - py) ^ 2)
outputs.string.status = "active"
end
function OnSpawned(request_id, entities)
if entities and #entities > 0 then
local bullet = entities[1]
local turret = Entity(inputs.entity.target)
if not turret._nil then
local nx, ny = turret:getNormal()
bullet:setVelocity(nx * 30, ny * 30)
bullet:setGravityScale(0)
bullet:freezeRotation(1)
bullet:setColor(1, 0.5, 0, 1)
end
end
end
function OnActivated()
print("turret activated")
end
function OnDeactivated()
print("turret deactivated")
end
function OnDestroy()
print("turret destroyed")
end22 Appendix A: Function Index
Compact signature list. Boolean-like returns are 1/0.
LIFECYCLE
OnInit() OnTick() OnActivated() OnDeactivated()
OnSpawned(request_id, entities) OnDestroy()
ENTITY CONSTRUCTION / IDENTITY
Entity(id) e._nil e:getId() e:isValid()
entity.all() entity.find(name)
ENTITY TRANSFORM
e:getPosition() e:setPosition(x, y)
e:getAngle() e:setAngle(angle)
e:getScale() e:setScale(x, y) e:getNormal()
e:localToWorld(x, y) e:worldToLocal(x, y)
e:localAngleToWorld(angle) e:worldAngleToLocal(angle)
ENTITY PHYSICS
e:getVelocity() e:setVelocity(vx, vy)
e:getAngularVelocity() e:setAngularVelocity(omega)
e:addForce(fx, fy) e:addTorque(torque)
e:addForceAtPosition(fx, fy, px, py) e:getVelocityAtPoint(x, y)
e:getMass() e:getCenterOfMass()
e:getGravityScale() e:setGravityScale(scale)
e:freeze(flag) e:freezeRotation(flag) e:setCollisionEnabled(flag)
ENTITY HEALTH / TEMPERATURE
e:getTemperature() e:setTemperature(value)
e:isOnFire() e:isFrozen() e:ignite() e:extinguish()
e:getHealth() e:isBreakable()
ENTITY VISUALS / ELECTRICITY / INTERACTION
e:getColor() e:setColor(r, g, b, [a])
e:getName() e:getLocalizedName()
e:isVisible() e:setVisible(flag)
e:getVoltage()
e:isDraggable() e:setDraggable(flag)
e:activate(flag) e:getActivationInput() e:delete()
ENTITY HIERARCHY / BOUNDS / EXTENDED
e:getRoot() e:getParent() e:getChildren()
e:getSize() e:getBaseSize()
e:getBounds() e:getFullBounds() e:getColliderBounds()
e:lookAt(target_id, speed) e:getElevation(x, y)
e:canBeActivated() e:getPhysicMaterial()
ENTITY EVENTS
e:subscribeCollisionEnter(fn(other, self, nx, ny))
e:subscribeCollisionExit(fn(other, self))
e:subscribeCollisionStay(fn(other, self))
e:subscribeTriggerEnter(fn(other, self))
e:subscribeTriggerExit(fn(other, self))
e:subscribeTriggerStay(fn(other, self))
e:unsubscribeCollisionEnter(sub_id) e:unsubscribeCollisionExit(sub_id)
e:unsubscribeCollisionStay(sub_id) e:unsubscribeTriggerEnter(sub_id)
e:unsubscribeTriggerExit(sub_id) e:unsubscribeTriggerStay(sub_id)
e:unsubscribeAll()
e:subscribeWireConnected(fn(self_id, input_key, output_entity_id, output_key))
e:subscribeWireDisconnected(fn(self_id, input_key))
e:unsubscribeWireConnected(sub_id) e:unsubscribeWireDisconnected(sub_id)
ENV
env.time() env.deltaTime() env.fixedDeltaTime()
env.timeScale() env.setTimeScale(scale)
env.frameCount() env.sessionTime() env.entityCount()
env.isWorld() env.isWorldEditor()
env.systemTime() env.systemDate()
env.toDate(days) env.toTimeFormat(seconds) env.parseDate(text)
env.getMapSize()
CAMERA
camera.getPosition() camera.setPosition(x, y)
camera.getZoom() camera.setZoom(value)
camera.follow(entity_id) camera.unfollow() camera.isFollowing()
INPUT
input.pointerDown() input.pointerUp()
input.pointerPos() input.pointerScreenPos() input.pointerDelta()
input.pointerRaycast() input.pointerRaycastAll()
input.isOverUI() input.pointerDownFiltered() input.pointerUpFiltered()
input.touchCount()
input.touchSet(i) input.touchDown(i) input.touchUp(i)
input.touchAge(i) input.touchId(i)
input.touchPos(i) input.touchScreenPos(i) input.touchStartScreenPos(i)
input.touchDelta(i) input.touchSwipeDelta(i)
input.touchTap(i) input.touchTapCount(i) input.touchSwipe(i)
input.touchIsOverUI(i) input.touchStartedOverUI(i)
input.pinchDistance([a, b]) input.pinchAngle([a, b]) input.pinchCenter([a, b])
input.key(name) input.keyDown(name)
SPAWN
spawn.getItems() spawn.getItemsString([sep]) spawn.getItemCount()
spawn.getSaves() spawn.getSavesString([sep]) spawn.getSaveCount()
spawn.getResourceSaves() spawn.getResourceSavesString([sep])
spawn.getResourceSaveCount()
spawn.getMods() spawn.getModsString([sep]) spawn.getModCount()
spawn.create(alias, x, y) spawn.createWithAngle(alias, x, y, angle)
spawn.clone(entity_id, x, y) spawn.cloneTemp(entity_id, x, y)
spawn.createSave(name, x, y) spawn.createMod(name, x, y)
spawn.destroy(entity_id)
spawn.getNameByAlias(alias) spawn.existsByAlias(alias)
CHIP
chip.has(id) chip.getType(id)
chip.getInputs(id) chip.getOutputs(id)
chip.getValue(id, gate) chip.setValue(id, gate, value) chip.hasWire(id, gate)
chip.getActivation(id) chip.setActivation(id, value)
chip.getName(id) chip.getTPS(id)
MECHANIC
mechanic.has(id) mechanic.getType(id)
mechanic.getInputs(id) mechanic.getOutputs(id)
mechanic.getValue(id, gate) mechanic.setValue(id, gate, value)
mechanic.hasWire(id, gate)
mechanic.getActivation(id) mechanic.setActivation(id, value)
UICONTROL
uicontrol.hasUIControl(panel) uicontrol.getElements(panel)
uicontrol.findElement(panel, name) uicontrol.getElementsByType(panel, type_name)
uicontrol.getInputGates(panel, element_id) uicontrol.getOutputGates(panel, element_id)
uicontrol.getValue(panel, element_id, gate)
uicontrol.setValue(panel, element_id, gate, value)
uicontrol.hasWire(panel, element_id, gate)
uicontrol.getAnchors(panel, element_id)
uicontrol.getAnchoredPosition(panel, element_id)
uicontrol.setAnchoredPosition(panel, element_id, x, y)
WORLD
world.isSessionActive() world.startSession() world.endSession()
world.save() world.load() world.reset()
world.clearCorpses() world.clearDecals() world.clearGibs() world.clearLiving()
world.radioSignal(channel)
VARIABLES / SHARED / SIGNAL / MODULES
variables.Set(name, value) variables.Get(name)
variables.SetGlobal(name, value) variables.GetGlobal(name)
shared.<key> shared.Save() shared.Load()
signal.on(name, fn) signal.emit(name, data)
signal.defer(name, data) signal.off(name, sub_id)
register_module(name, table) require(name)
DIAGNOSTICS
print(...) warn(...) error_log(...)
PINS
inputs.<family>.<name> outputs.<family>.<name>
families: num int string vec color entity
array_num array_string array_vec array_entity23 Appendix B: Compatibility Notes
The following behaviors are not fully specified by the available API description. Use the conservative behavior shown here and verify uncertain cases in the current game version.
| No. | Topic | Note |
|---|---|---|
| 1 | First argument of spawn.create | Use an alias string obtained from spawn.getItems. The behavior of numeric arguments is unspecified; do not rely on it. |
| 2 | Return values of getBounds | Center x, center y, width, height |
| 3 | Entry format of spawn.getSaves | Entries are name|id strings; the first field is the name used by spawn.createSave |
| 4 | UIControl element type names | Read the exact type string from uicontrol.getElements and pass that exact value to getElementsByType. Do not assume numbered and unnumbered names are interchangeable. |
| 5 | Parameter of env.toTimeFormat | Accepts a number of seconds |
| 6 | Return of variables.Set | 1 on success; otherwise 0 plus a message |
| 7 | Persistence of variables.SetGlobal | Not specified |
| 8 | shared.Save / shared.Load | Serialize to and load from GlobalVariables in worlds; test persistence in your world before relying on it |
| 9 | Methods on a nil entity | Behavior is unspecified. Check e._nil and, where appropriate, e:isValid() == 1 before calling methods. |
| 10 | OnActivated trigger conditions | One activation performs one callback invocation; no further guarantees are made |
| 11 | Pin naming case | Use the exact pin name referenced in the script and displayed by the editor. Do not assume case conversion. |
24 Appendix C: Unsupported API Names
| Removed | Replacement |
|---|---|
screen.size(), screen.center() | none documented |
time.now(), time.delta(), time.realtime(), time.frame() | env.time(), env.deltaTime(), env.frameCount() |
go.*, physics.*, sprite.*, event.* | Entity API; signal |