Melon Sandbox: Lua Chip Programming Reference

Document type
Technical reference
Subject
Lua scripting API of the Lua Chip mechanic in Melon Sandbox
Language of the scripting environment
Lua (sandboxed; restricted standard library)

Contents

  1. 1 Introduction
  2. 2 Execution Model and Lifecycle
  3. 3 Language Conventions
  4. 4 Typed Inputs and Outputs
  5. 5 Entity API
  6. 6 env Module
  7. 7 camera Module
  8. 8 input Module
  9. 9 spawn Module
  10. 10 chip Module
  11. 11 mechanic Module
  12. 12 uicontrol Module
  13. 13 world Module
  14. 14 variables Module
  15. 15 shared Table
  16. 16 signal Module
  17. 17 Custom Modules
  18. 18 Diagnostics
  19. 19 Standard Library
  20. 20 Programming Patterns
  21. 21 Complete Example
  22. 22 Appendix A: Function Index
  23. 23 Appendix B: Compatibility Notes
  24. 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:

NamespaceRole
Entity(id)Object wrapper: transform, physics, health, visuals, events
entityStatic entity functions (count, search)
envTime, session, date, map
cameraCamera position, zoom, following
inputPointer, multi-touch, gestures, keyboard
spawnCatalogs and creation of objects, saves, mods
chipIntrospection and I/O of other VPChip / LuaChip mechanics
mechanicIntrospection and I/O of standard (non-chip) mechanics
uicontrolRuntime access to UIControl panels
worldSession, persistence, cleanup, radio
variablesChip-level and global persistent variables
sharedTable shared between all chips
signalEvent bus between chips
register_module, requireCode sharing between chips
print, warn, error_logDiagnostics
inputs, outputsTyped 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 form module.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

  1. Write the required input and output references in the script so the corresponding typed pins can be exposed by the Lua Chip.
  2. Connect compatible output and input gates in the in-game editor. Use the pin family that matches the value being transferred.
  3. Read inputs inside OnTick or an appropriate callback. Supply defaults for unconnected scalar inputs.
  4. Validate entity IDs before calling entity methods. For UIControl, validate the panel entity with uicontrol.hasUIControl.
  5. Write output values during each tick in which they are needed. Use callbacks for deferred spawning and event subscriptions for collision or trigger events.

Back to contents

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

CallbackRequiredInvocation
(top-level code)n/aOnce, at first compilation
OnInit()NoOnce, after the first execution of the chunk and before the first OnTick
OnTick()YesEvery tick
OnActivated()NoWhen the chip is activated
OnDeactivated()NoWhen the chip is deactivated
OnSpawned(request_id, entities)NoWhen a deferred spawn request completes
OnDestroy()NoWhen the chip is destroyed

2.3 Ordering Guarantees

  1. Entity collision, trigger and wire subscription callbacks are invoked before OnTick, in a pre-execute hook.
  2. Signals sent with signal.defer are delivered at the beginning of the next tick.
  3. Spawn requests are deferred; their results arrive in OnSpawned, not at the call site.

2.4 State Persistence

StorageScopeSurvives recompilation / scene reloadWritten to disk
Script-level local variablesSingle chipNoNo
variables.Set / variables.GetSingle chipConditional (see Section 14)Conditional
variables.SetGlobal / variables.GetGlobalAll chipsNot specifiedNot specified
shared tableAll chipsOnly 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

lua
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()
end

2.6 Error Reporting

The engine reports script errors automatically to the console:

plain text
[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.

Back to contents

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:

lua
local name = e:getName() or "?"
local parent_id = e:getParent() or 0

3.3 Multiple Return Values

Position-like and size-like functions return several values:

lua
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

QuantityUnit
AnglesDegrees
Angular velocityDegrees per second
TimeSeconds
World coordinatesWorld units
Screen coordinatesPixels
Color components0..1
Anchors (uicontrol)0..1

3.6 Descriptor Strings

Introspection functions return arrays of strings with a | separator:

SourceFormat
chip.getInputs, chip.getOutputskey|GateDataType
mechanic.getInputs, mechanic.getOutputskey|GateDataType
uicontrol.getElementsname|type|id
uicontrol.getInputGates, uicontrol.getOutputGatesname|type
spawn.getItemsname|alias
spawn.getSaves, spawn.getResourceSaves, spawn.getModsname|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()).

Back to contents

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:

FamilyLua representationNotes
numnumber (double)Floating-point
intnumber (integer)Integer
stringstring
vectable {x, y, z, w}Four components
colortable {r, g, b, a}Components 0..1
entitynumberinstanceID; wrap with Entity()
array_numtable of numbers1-indexed
array_stringtable of strings1-indexed
array_vectable of {x, y, z, w}1-indexed
array_entitytable of instanceIDs1-indexed

Access form: inputs.<family>.<pin_name> and outputs.<family>.<pin_name>.

4.2 Rules

  1. Sub-tables always exist. inputs.num, inputs.vec, and so on are never nil; access is nil-safe at the family level.
  2. Unconnected inputs are nil (scalar types). Supply defaults with or.
  3. Array inputs default to an empty table when written as inputs.array_num.values or {}.
  4. 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.
  5. 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.
  6. Unused vector components are set to 0.
  7. Entity pins carry an instanceID. A missing entity is nil or 0.

4.3 Scalar Example

lua
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
end

4.4 Array Example

lua
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 }
end

4.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:

lua
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
end

4.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.

lua
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
end

An 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.

Back to contents

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.

MemberParametersReturnsDescription
Entity(id)id: instanceIDentity objectWraps an instanceID
e._nilnone (field)boolean-likeTruthy when the entity is absent; always test before use
e:getId()nonenumberinstanceID
e:isValid()none1/01 if the object is alive
lua
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
end

Entities captured in long-lived structures can be destroyed in the meantime. Validate with isValid() before use, for example in OnDestroy.

5.2 Transform

MethodParametersReturnsDescription
getPosition()nonex, yWorld position
setPosition(x, y)x, ynoneSet world position
getAngle()nonedegreesWorld angle
setAngle(angle)degreesnoneSet world angle
getScale()nonescale_x, scale_yScale
setScale(x, y)x, ynoneSet scale
getNormal()nonex, yUp vector of the object
localToWorld(x, y)local x, yworld x, yCoordinate conversion
worldToLocal(x, y)world x, ylocal x, yCoordinate conversion
localAngleToWorld(angle)degreesdegreesAngle conversion
worldAngleToLocal(angle)degreesdegreesAngle conversion

5.3 Physics

MethodParametersReturnsDescription
getVelocity()nonevx, vyLinear velocity
setVelocity(vx, vy)vx, vynoneSet linear velocity
getAngularVelocity()nonedegrees/sAngular velocity
setAngularVelocity(omega)degrees/snoneSet angular velocity
addForce(fx, fy)fx, fynoneApply a force (world)
addTorque(torque)torquenoneApply torque
addForceAtPosition(fx, fy, px, py)force, world pointnoneApply a force at a point
getVelocityAtPoint(x, y)world pointvx, vyVelocity at a world point
getMass()nonenumberMass
getCenterOfMass()nonex, yCenter of mass (world)
getGravityScale()nonenumberGravity multiplier
setGravityScale(scale)scalenone0 disables gravity, 1 restores it
freeze(flag)1/0none1 static body, 0 dynamic body
freezeRotation(flag)1/0none1 forbids rotation, 0 allows it
setCollisionEnabled(flag)1/0none0 moves the object to the NoCollide layer, 1 restores the layer

Forces are typically applied every tick for a sustained effect:

lua
function OnTick()
    local e = Entity(inputs.entity.target)
    if e._nil then return end
    e:addForce(0, 500)
end

5.4 Health and Temperature

MethodParametersReturnsDescription
getTemperature()nonenumberTemperature
setTemperature(value)numbernoneSet temperature
isOnFire()none1/0Burning state
isFrozen()none1/0Frozen state
ignite()nonenoneSet on fire
extinguish()nonenoneExtinguish
getHealth()nonenumberHealth
isBreakable()none1/0Whether the object can be broken

Guard these getters with or 0: a result may be nil for objects lacking the component.

5.5 Visuals

MethodParametersReturnsDescription
getColor()noner, g, b, aColor, each 0..1
setColor(r, g, b, [a])r, g, b, optional anoneAlpha defaults to 1
getName()nonestringInternal ObjectName
getLocalizedName()nonestringLocalized name
isVisible()none1/0Visibility (InvisibleComponent); 0 = hidden
setVisible(flag)1/0noneHide (0) or show (1)
lua
function OnTick()
    local e = Entity(inputs.entity.target)
    if e._nil or e:isValid() ~= 1 then return end
    e:setColor(0, 1, 0, 1)
end

5.6 Electricity

MethodParametersReturnsDescription
getVoltage()nonenumberVoltage

5.7 Interaction

MethodParametersReturnsDescription
isDraggable()none1/0Whether the object can be dragged
setDraggable(flag)1/0noneForbid (0) or allow (1) dragging
activate(flag)1/0noneActivate (1) or deactivate (0) the object’s mechanic
getActivationInput()nonenumberCurrent activation value
delete()nonenoneDestroy the object

5.8 Identity and Static Functions

FunctionParametersReturnsDescription
e:getId()nonenumberinstanceID
e:isValid()none1/0Liveness
entity.all()nonenumberNumber of objects in the scene
entity.find(name)stringnumber or nilinstanceID of the first object with this name

Note: the namespace entity (lowercase, static functions) is distinct from the constructor Entity (capitalized).

5.9 Hierarchy

MethodParametersReturnsDescription
getRoot()noneinstanceIDTopmost object with Properties in the hierarchy; the object’s own id if it is already the root
getParent()noneinstanceID or nilNearest parent with Properties
getChildren()nonearray of instanceIDsDirect children only (one level); may be empty
lua
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
end

5.10 Bounds

MethodParametersReturnsDescription
getSize()nonewidth, heightActual size = base size multiplied by scale; cached; independent of rotation
getBaseSize()nonewidth, heightSize at scale 1
getBounds()nonecenter_x, center_y, width, heightWorld AABB of the first renderer; depends on rotation
getFullBounds()nonecenter_x, center_y, width, heightWorld AABB of all renderers
getColliderBounds()nonecenter_x, center_y, width, heightWorld AABB of the collider

5.11 Extended Functions

MethodParametersReturnsDescription
lookAt(target_id, speed)instanceID, degrees/snoneRotate toward the target at the given angular speed
getElevation(x, y)world pointdegreesAngle from the entity to the point
canBeActivated()none1/0Whether the entity has a Mechanic
getPhysicMaterial()nonestringPhysics 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.

MethodCallback signatureDescription
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.

UnsubscriptionParameters
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
lua
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
end

Subscribe 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.

MethodCallback signatureDescription
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)idRemove the subscription
unsubscribeWireDisconnected(sub_id)idRemove the subscription

Back to contents

6 env Module

Environment, time, session and map information.

FunctionReturnsDescription
env.time()secondsScaled game time (Time.time)
env.deltaTime()secondsFrame delta (Time.deltaTime)
env.fixedDeltaTime()secondsFixed physics step (Time.fixedDeltaTime)
env.timeScale()numberCurrent time scale
env.setTimeScale(scale)noneSet time scale; documented range 0..2
env.frameCount()numberFrame number
env.sessionTime()secondsTime since the session started
env.entityCount()numberNumber of objects in the scene
env.isWorld()1/0Whether the context is a world
env.isWorldEditor()1/0Whether the context is the world editor
env.systemTime()secondsUTC seconds since the epoch
env.systemDate()daysUTC days since the epoch
env.toDate(days)stringFormats days as dd.MM.yyyy
env.toTimeFormat(seconds)stringFormats seconds as HH:MM:SS
env.parseDate(text)daysParses dd.MM.yyyy into days since the epoch; 0 on failure
env.getMapSize()x, yMap size; -1, -1 if the map is infinite
lua
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 }
end

Back to contents

7 camera Module

FunctionParametersReturnsDescription
camera.getPosition()nonex, yCamera position
camera.setPosition(x, y)x, ynoneSet position; ignored while following
camera.getZoom()nonenumberZoom value
camera.setZoom(value)numbernoneSet zoom value
camera.follow(entity_id)instanceIDnoneFollow an entity
camera.unfollow()nonenoneStop following
camera.isFollowing()none1/0Following 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.

lua
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
end

Back to contents

8 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.

FunctionReturnsDescription
input.pointerDown()1/0Pointer pressed
input.pointerUp()1/0Pointer released in this frame
input.pointerPos()x, yWorld coordinates
input.pointerScreenPos()x, yScreen pixels
input.pointerDelta()dx, dyMovement delta per frame (pixels)

8.2 Raycast

FunctionReturnsDescription
input.pointerRaycast()instanceIDFirst object under the pointer; 0 if none
input.pointerRaycastAll()array of instanceIDsAll objects under the pointer; unique
lua
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
end

8.3 UI Filtering

FunctionReturnsDescription
input.isOverUI()1/0Pointer is over UI
input.pointerDownFiltered()1/0Pressed, and the press did not start over UI
input.pointerUpFiltered()1/0Released, 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.

FunctionReturnsDescription
input.touchCount()numberNumber of active fingers
input.touchSet(i)1/0Finger is touching now
input.touchDown(i)1/0Pressed in this frame
input.touchUp(i)1/0Released in this frame
input.touchAge(i)secondsTime since the touch began
input.touchId(i)numberStable hardware id
input.touchPos(i)x, yWorld coordinates
input.touchScreenPos(i)x, yCurrent screen pixels
input.touchStartScreenPos(i)x, yScreen position at touch start
input.touchDelta(i)dx, dyDelta per frame
input.touchSwipeDelta(i)dx, dyTotal displacement since touch start
input.touchTap(i)1/01 only in the frame of a tap event
input.touchTapCount(i)numberConsecutive taps (double tap = 2)
input.touchSwipe(i)1/01 only in the frame of a swipe event
input.touchIsOverUI(i)1/0Currently over UI
input.touchStartedOverUI(i)1/0Started 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).

FunctionReturnsDescription
input.pinchDistance([a, b])pixelsDistance between the fingers; 0 if fewer than two
input.pinchAngle([a, b])degreesAngle from finger a to finger b (rotation gesture)
input.pinchCenter([a, b])x, yCenter between the fingers in screen space

Pinch-zoom is implemented by tracking the change of distance between ticks (positive change = fingers moving apart):

lua
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
end

8.6 Keyboard

FunctionReturnsDescription
input.key(name)1/0Key is held
input.keyDown(name)1/0Key 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".

lua
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
end

Back to contents

9 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

FunctionReturnsEntry format
spawn.getItems()array of stringsname|alias
spawn.getItemsString([separator])stringJoined entries; default separator ", "
spawn.getItemCount()numberCount
spawn.getSaves()array of stringsUser saves
spawn.getSavesString([separator])stringJoined entries
spawn.getSaveCount()numberCount
spawn.getResourceSaves()array of stringsBuilt-in saves from resources
spawn.getResourceSavesString([separator])stringJoined entries
spawn.getResourceSaveCount()numberCount
spawn.getMods()array of stringsMods
spawn.getModsString([separator])stringJoined entries
spawn.getModCount()numberCount

Entries of the form name|key are split with entry:match("^([^|]+)") to obtain the name.

9.2 Object Creation

FunctionParametersReturnsDescription
spawn.create(alias, x, y)alias string, world x, yrequest idCreate a standard object
spawn.createWithAngle(alias, x, y, angle)alias, x, y, degreesrequest idCreate with a rotation

9.3 Cloning

FunctionParametersReturnsDescription
spawn.clone(entity_id, x, y)instanceID, x, yrequest idClone (persisted)
spawn.cloneTemp(entity_id, x, y)instanceID, x, yrequest idTemporary clone (not persisted)

9.4 Saves and Mods

FunctionParametersReturnsDescription
spawn.createSave(name, x, y)save name, x, yrequest idSpawn a save; OnSpawned receives all of its entities
spawn.createMod(name, x, y)mod name, x, yrequest idSpawn a mod; OnSpawned receives all of its entities

9.5 Destruction

FunctionParametersReturnsDescription
spawn.destroy(entity_id)instanceIDnoneImmediate removal

9.6 Alias Lookup

FunctionParametersReturnsDescription
spawn.getNameByAlias(alias)aliasstringLocalized name; empty or nil for an unknown alias
spawn.existsByAlias(alias)alias1/0Whether the alias exists

9.7 The OnSpawned Callback

plain text
OnSpawned(request_id, entities)
ParameterDescription
request_idThe number returned by the originating spawn.* call
entitiesArray of entity objects (always an array, even for one object); nil on error
lua
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
end

Back to contents

10 chip Module

Introspection and gate access for VPChip and LuaChip mechanics. For UIControl panels use uicontrol; for other mechanics use mechanic.

FunctionParametersReturnsDescription
chip.has(id)instanceID1/0Whether the entity is a chip
chip.getType(id)instanceID"VPChip", "LuaChip" or nilChip kind
chip.getInputs(id)instanceIDarray of key|GateDataType or nilInput gates
chip.getOutputs(id)instanceIDarray of key|GateDataType or nilOutput gates
chip.getValue(id, gate)id, gate namevalue or nilReads a gate; outputs are searched first, then inputs
chip.setValue(id, gate, value)id, gate name, value1/0Writes a gate; 0 if the gate is connected by a wire
chip.hasWire(id, gate)id, gate name1/0Whether a wire is attached to the input gate
chip.getActivation(id)instanceIDnumberCurrent ActivationInput
chip.setActivation(id, value)id, value1/0Writes ActivationInput
chip.getName(id)instanceIDstringVisual name or __name input
chip.getTPS(id)instanceIDnumberTicks 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.

lua
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)
end

Back to contents

11 mechanic Module

Introspection and gate access for standard mechanics (guns, doors, thrusters, timers, motors, buttons). The module excludes VPChip, LuaChip and UIControlMechanic.

FunctionParametersReturnsDescription
mechanic.has(id)instanceID1/0Whether the entity has a standard mechanic
mechanic.getType(id)instanceIDstring or nilMechanic class name
mechanic.getInputs(id)instanceIDarray of key|type or nilInput gates
mechanic.getOutputs(id)instanceIDarray of key|type or nilOutput gates
mechanic.getValue(id, gate)id, gate namevalue or nilReads a gate
mechanic.setValue(id, gate, value)id, gate name, value1/0Writes a gate; 0 if wired or unknown
mechanic.hasWire(id, gate)id, gate name1/0Wire attached
mechanic.getActivation(id)instanceIDnumberActivationInput
mechanic.setActivation(id, value)id, value1/0Writes ActivationInput

Value types accepted by setValue, chosen according to the gate type in the descriptor:

Gate typeValue
Number, IntegerNumbernumber
Stringstring
Vector, Colortable {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.

lua
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
end

Back to contents

12 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.

FunctionReturnsDescription
uicontrol.hasUIControl(panel)1/0Whether the entity has a UIControl
uicontrol.getElements(panel)array of name|type|id or nilAll elements
uicontrol.findElement(panel, name)element idElement lookup by name
uicontrol.getElementsByType(panel, type_name)array of element idsElements of a type
uicontrol.getInputGates(panel, element_id)array of name|type or nilInput gates of an element
uicontrol.getOutputGates(panel, element_id)array of name|type or nilOutput gates of an element
uicontrol.getValue(panel, element_id, gate)value or nilReads a gate
uicontrol.setValue(panel, element_id, gate, value)1/0Writes a gate; 0 if wired or unknown
uicontrol.hasWire(panel, element_id, gate)1/0Wire attached to the gate
uicontrol.getAnchors(panel, element_id)min_x, min_y, max_x, max_yRectTransform anchors, 0..1
uicontrol.getAnchoredPosition(panel, element_id)x, yAnchored position
uicontrol.setAnchoredPosition(panel, element_id, x, y)noneMove the element at runtime

Element descriptors have the form name|type|id; the id is the third field:

lua
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"
end

Edge 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.

lua
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")
end

Back to contents

13 world Module

FunctionReturnsDescription
world.isSessionActive()1/0Whether a session is active
world.startSession()noneStart a session
world.endSession()noneEnd the session
world.save()noneSave the current state
world.load()noneLoad the last save
world.reset()noneReset to the initial state
world.clearCorpses()noneRemove corpses
world.clearDecals()noneRemove decals (blood, traces)
world.clearGibs()noneRemove debris
world.clearLiving()noneRemove living beings
world.radioSignal(channel)numberSignal value on a radio channel

Back to contents

14 variables Module

Named values stored through the gate-data system.

FunctionParametersReturnsDescription
variables.Set(name, value)string, valueok, errorok is 1 on success; on failure 0 and an error message
variables.Get(name)stringvalue or nilChip-level read
variables.SetGlobal(name, value)string, valueok, errorGlobal write
variables.GetGlobal(name)stringvalue or nilGlobal read

Characteristics:

  1. Chip-level variables are held in the VariablesGateDataComponent of the owning chip.
  2. The type of a variable is fixed at creation: a Number remains a Number.
  3. 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.
  4. For data exchange between chips use shared, signal or register_module rather than variables.
lua
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
end

Back to contents

15 shared Table

shared is a table visible to every chip. It holds values of any Lua type, including nested tables.

OperationDescription
shared.key = valueWrite
shared.keyRead; nil if absent
shared.Save()Serialize to GlobalVariables (in worlds)
shared.Load()Load from GlobalVariables (in worlds)
lua
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")
end

15.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

  • shared is 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() and shared.Load() persist through GlobalVariables in worlds; see Appendix B.

Back to contents

16 signal Module

An event bus between chips. Payloads may be any Lua value.

FunctionParametersReturnsDescription
signal.on(name, fn)event name, fn(data)subscription idSubscribe. Call once, in OnInit or at top level
signal.emit(name, data)name, payloadnoneImmediate delivery: all subscribers are called at once
signal.defer(name, data)name, payloadnoneDelivery at the beginning of the next tick
signal.off(name, sub_id)name, idnoneUnsubscribe
lua
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
end

Back to contents

17 Custom Modules

Chips share reusable code through a registry.

FunctionParametersDescription
register_module(name, table)string, tablePublish a module; may contain functions, tables, numbers, any Lua value
require(name)stringImport 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:

lua
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,
    })
end
lua
function 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)
end

Back to contents

18 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.

FunctionLevelIntended use
print(...)InfoDiagnostics and ordinary tracing; multiple arguments are separated by tabs
warn(...)WarningNon-critical problem requiring attention
error_log(...)ErrorA genuine defect or unrecoverable condition
lua
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
end

Compilation 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:

lua
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
end

Back to contents

19 Standard Library

The following standard-library members are documented for use in the Lua Chip environment:

LibraryMembers
mathabs, floor, ceil, sqrt, sin, cos, atan2, pi, max, min, random, huge
stringlen, sub, find, format, rep, upper, lower, byte, char, gmatch, match
tableinsert, remove, sort, concat, unpack
coroutinecreate, resume, yield, status
basepairs, 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

lua
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
end

20.2 Command Selector With Change Detection

lua
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
end

20.3 Rising-Edge Toggle

lua
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
end

20.4 Subscribe Once

lua
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
end

20.5 One-Shot Execution

lua
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))
end

20.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.

lua
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" })
end

Consumer:

lua
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
end

20.7 Distance Between Entities

lua
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)
end

20.8 Rate Limiting With env.time

lua
local last_fire = 0

function OnTick()
    local now = env.time()
    if now - last_fire > 0.5 then
        last_fire = now
        print("fire")
    end
end

Back to contents

21 Complete Example

An automatic turret. Pins: entity target (turret), entity other (aim target), string bullet_alias. Outputs: number distance, string status.

lua
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")
end

Back to contents

22 Appendix A: Function Index

Compact signature list. Boolean-like returns are 1/0.

plain text
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_entity

Back to contents

23 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.TopicNote
1First argument of spawn.createUse an alias string obtained from spawn.getItems. The behavior of numeric arguments is unspecified; do not rely on it.
2Return values of getBoundsCenter x, center y, width, height
3Entry format of spawn.getSavesEntries are name|id strings; the first field is the name used by spawn.createSave
4UIControl element type namesRead the exact type string from uicontrol.getElements and pass that exact value to getElementsByType. Do not assume numbered and unnumbered names are interchangeable.
5Parameter of env.toTimeFormatAccepts a number of seconds
6Return of variables.Set1 on success; otherwise 0 plus a message
7Persistence of variables.SetGlobalNot specified
8shared.Save / shared.LoadSerialize to and load from GlobalVariables in worlds; test persistence in your world before relying on it
9Methods on a nil entityBehavior is unspecified. Check e._nil and, where appropriate, e:isValid() == 1 before calling methods.
10OnActivated trigger conditionsOne activation performs one callback invocation; no further guarantees are made
11Pin naming caseUse the exact pin name referenced in the script and displayed by the editor. Do not assume case conversion.

Back to contents

24 Appendix C: Unsupported API Names

RemovedReplacement
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

Back to contents