Lua scripting overview
Use lifecycle callbacks, input, gameObject, scene, multiplayer, and gameStorage safely.
New to Lua, or reading a script someone else wrote? Open it and press Explain script in the Edit Script dialog, or select some lines and press Explain lines N–M, for a walk-through of what the code does and the engine calls it uses. See "Explaining a script" in Editor basics.
Object-script lifecycle
function init()
-- Runs once when simulation starts.
end
function update(deltaTime)
-- Runs once per simulation step (once a frame at 30 fps or better).
end
function destroy()
-- Runs when simulation stops or the scene changes.
end
Each run starts the script afresh. Whether it is Run in the editor or a physics_run_simulation call, the whole script runs again before init(), so a top-level local starts every run at its initial value, not where the previous run left it.
deltaTime is game time: the seconds of game that passed this step, which follow the scene's time scale. A step covers at most 1/30 of a real second. At 30 fps or better that is one step per frame; in single player a slower frame runs several equal steps, up to half a second's worth, and update runs once for each of them, so add up deltaTime rather than counting calls. In slow motion it is smaller than the real step, and at a time scale of 0 it is 0. scene.getUnscaledDeltaTime() gives the real seconds; see Time scale and slow motion.
Optional callbacks include onCollisionEnter, onCollisionExit, onTriggerEnter, onTriggerExit, onCollisionStay (once a frame for each solid contact that keeps touching, for scripts that define it; see Collision callbacks), onClick for scripted GUI objects, onValueChanged(value, final) for a guiSlider's script when the player moves it (at most once per frame; final is true when the drag ends or a key is pressed; see Sliders), and onAnimationFinished(name), called once when a clip the object played with loop=false reaches its end, and onAnimationMarker(clip, name, time) and onAnimationTimelineFinished(clip) for an animation timeline the script started, and onAnimationLayerFinished(layer, clip), called once when a one-shot clip on one of the object's animation layers reaches its end; layer clips never call onAnimationFinished (see Animation playback API).
Which objects run scripts
Every object type runs init(), update() and destroy(). There is no type filter and no requirement that the object have a physics body, a mesh, or a visible presence — an empty with no collider ticks exactly like a cube does. If a script appears not to run, the cause is almost never the object's type.
| Object | init / update / destroy | Collision and trigger callbacks |
|---|---|---|
| Cube, sphere, capsule, mesh, character, and other physical objects | Yes | Yes, after registerForCollisions() |
empty (no collider) | Yes | No — no body, so no contacts exist to report |
camera | Yes, but see the warning below | No |
GUI objects (guiLabel, guiButton, guiPanel, guiImage, guiSlider, guiProgressBar) | Yes | No, but they receive onClick, and a slider onValueChanged |
particleEmitter | Yes; in a multiplayer room always as presentation | No — an emitter has no collider |
| Scene script | Yes, and runs after all object scripts each frame | No |
onCollisionEnter, onCollisionExit, onTriggerEnter and onTriggerExit require gameObject.registerForCollisions() in that object's own init(). Registering on one object does not enroll any other. An object with no collider can never receive them however it is registered — update() still runs, only the contact callbacks are unavailable. An overlap with a trigger volume calls onTriggerEnter/onTriggerExit; if the script defines neither, it falls back to onCollisionEnter/onCollisionExit, so an older collision-only script keeps working when its object is made a sensor.
Cameras with scripts stop following
A camera object runs its script like anything else, but attaching a script switches off the engine's built-in camera controller for that camera. A first_person or third_person camera with a scriptId silently stops following its target. See Cameras and follow modes.
One script per object
An object has exactly one scriptId. There is no way to attach several scripts to one object, so behaviour that spans concerns is split across cooperating objects, or hosted on the scene script, and coordinated through object lookups or variables. See Cross-object interactions.
The scene global differs between object and scene scripts
Both kinds of script get a scene global, but they are not the same object. Every object script can call loadScene, restart, pauseGame, resumeGame, getActiveCamera, setActiveCamera, getVar, setVar, findPath, getNearestNavPoint, and the clock reads getTimeScale, getUnscaledDeltaTime, getTime, and getUnscaledTime, and getStartReason, which says whether the run started from a page load, a restart, or a scene change (see Game storage). A scene script carries all of that plus the lookup, spawning, cloning, gravity, time scale, logging, and scene-audio calls below.
scene.getObjectByName is not the lookup you want in an object script
Object lookup exists in both contexts, but under different globals. In an object script it is on gameObject — gameObject.getObjectByName("Player"). Only a scene script also has it on scene. Reaching for scene.getObjectByName in an object script raises "attempt to call a nil value (field 'getObjectByName')" and stops the rest of that callback, which is a confusing failure because the call is real and documented, just under the other global.
These are on gameObject and available to every object script: getObject, getObjectByName, getObjectsByNamePrefix, getObjectsByType, positional playSound / stopSound / isSoundPlaying, and destroy() on any handle you have resolved.
What genuinely requires a scene script is a shorter list than it looks:
createObject— spawning is scene-script-only. Destroying is not: every object handle carries its owndestroy(), so an object script can remove anything it can resolve, andgameObject.destroy()removes itself.cloneObject— copying an object and everything under it as runtime objects.getGravity,setGravity,getGravityAtandsetRadialGravity.setTimeScale. Reading the scale and the clocks is open to every script.log.
Music and non-positional sound are not on that list: scene.playMusic, stopMusic, playSound, stopAllSounds, setMusicVolume, setSfxVolume, setSoundFilter, setSfxFilter, setMusicFilter and setReverb are on an object script's scene too. An object script's gameObject.playSound plays at that object instead.
Prefer resolving a handle once in init() and caching it over routing a value through a variable. You then read the live object rather than a value someone else has to remember to update. Reserve variables for state with no owning object, such as a score or a shield total.
Global APIs
gameObject: the object the script is attached to, plus object lookup and per-object audio.scene: scene transitions, the active camera and scene variables for object scripts; the full scene API for scene scripts. See above.tween: simulation-time transform and numeric interpolation; see Simulation-time tweens.timer: simulation-time delays and repeats; see Simulation-time timers.input: shared keyboard, pointer, gamepad, and mobile control state.gameStorage: values saved for the current game on the player's device. In a published game they also sync to a signed-in player's account;gameStorage.syncState()reports where the save is, andgameStorage.useSlot(n)switches the other calls to save slot 0, 1 or 2 (see Saves across devices). Saved values survive a restart, so checkscene.getStartReason()before resuming saved progress. In a multiplayer room only GUI, camera, and presentation scripts may use it.player:startSolo()andopenMultiplayer()for buttons in an authored local menu. Both returnok, reasonand take no arguments. The published multiplayer action opens the existing picker; Local Preview returnsfalse, "multiplayer_unavailable", andstartSolo()returnsfalse, "solo_unavailable"when a multiplayer game's Game startup settings do not allow play without a room.player.markGameplayStarted()records that play began inside the current scene without changing scenes. The same global carries the touch-overlay overridessetTouchDisplay,setTouchEnabledandsetTouchLabeland theirclear…counterparts; see Player input and touch controls. All of these are presentation calls. See Menu scenes and player actions.multiplayer: rooms, actions, combat, shared state, and events. See below.print(...): writes to the browser's developer console, prefixed with where it came from —[object Player]for an object script,[scene]for the scene script.
Simulation-time timers
Object and scene scripts receive a timer global. timer.after(seconds, callback) runs the callback once after seconds of game time; timer.every(seconds, callback) runs it every seconds. Both return a handle with handle:cancel(), and cancelling twice is harmless. timer.cancelAll() cancels every timer in that script, including callbacks already due.
timer.after(2, function()
scene.setVar("doorsOpen", true)
end)
local pulse = timer.every(1, function()
gameObject.setText("Time: " .. math.floor(scene.getTime()))
end)
-- later
pulse:cancel()
seconds must be a finite number: after accepts zero or more, every needs a positive interval. At most 256 timers may be live in one script; a bad argument or the limit raises a Lua error. Timers run on game time, so they follow the scene's time scale and stop while the game is paused, and they advance before update(deltaTime) each step: due callbacks run by deadline, then creation order. A timer with zero delay, or one created inside a callback, waits for the next step. A repeating timer runs at most once per step and skips repeats a long frame missed rather than catching up in a burst. Stop, the object's destruction and a scene change clear pending timers, so schedule them in init(). An error in one callback is reported through the usual script diagnostics and does not skip later callbacks or update.
Simulation-time tweens
Object and scene scripts receive a tween global for changes that should take a fixed amount of game time. Schedule a tween once in init() or in response to an action, rather than starting it again in every update().
local movement
function init()
local start = gameObject.getPosition()
movement = tween.to(gameObject, {
position = { y = start.y + 3 },
duration = 2,
easing = "inOutQuad",
onComplete = function()
print("Arrived")
end,
})
end
Attach this example to a kinematic platform or a static decoration. It moves upward three metres over two simulation seconds; omitted position axes keep their starting values. Dynamic rigid bodies, characters and soft bodies cannot use transform tweens: use forces, velocity or their movement APIs instead.
movement:cancel() stops this tween at its last sample without calling onComplete. tween.cancelAll() cancels every tween in this script. Stop, runtime destruction and scene replacement clear pending tweens, so schedule them in init() to restart them with each run.
Use tween.value(from, to, duration, easing, callback) for a finite numeric value. The callback receives each sample, including the final value. For example, this belongs in a GUI object's script:
function init()
tween.value(0, 1, 0.5, "outQuad", function(alpha)
gameObject.setOpacity(alpha)
end)
end
Duration is finite, non-negative game seconds. Tweens follow simulation pause and time scale, without reading wall-clock time. Timers run first, then tween samples in creation order, then the script's animation timeline and update(deltaTime). A tween created during a callback waits until the next step. Zero duration applies its final target on the next step; kinematic position or rotation needs a positive deltaTime. A callback error cancels that tween, is reported through the usual script diagnostics, and leaves later jobs and update runnable. At most 256 tweens may be live in one script.
See Transform tweens for rotation, scale, easing names, overlap and physics rules, and Tweens and prediction for room permissions and replay.
Input fields
The input table is filled in before a script's top-level code and init() run and refreshed before every update(), so input.device can be read in init() to choose a prompt. In a multiplayer room an authority object sees its validated command or neutral defaults there, and the scene script and a predicted copy start neutral.
The shared input bus includes moveForward, moveBackward, moveLeft, moveRight, lookUp, lookDown, lookLeft, lookRight, jump, primaryFire, and crouch. moveAxisX and moveAxisY report horizontal and forward/backward movement from -1 to 1, for smoother control than the booleans give. moveSprint is true while the movement stick is pushed to its rim, and after a gamepad's left stick is clicked until that stick returns to rest.
In a multiplayer room a control script also gets input.aimYaw and input.aimPitch: the player's aim from the command being simulated, in world-space radians. Yaw is measured from +Z toward +X, and positive pitch looks up. They are the same on the room server and in the player's own prediction replay, so turn a character from them rather than from a camera. Both are nil in solo play and on input with no multiplayer command, so check before using them. The exception is an object played by a bot (see Played by a bot): its control script gets the bot's aim in solo play too.
input.device is the device the player last used on purpose: "keyboard" (keyboard and mouse), "gamepad" or "touch". input.gamepadStyle is "xbox", "playstation", "nintendo" or "generic" for the last gamepad used, and nil until one is. Both are strings for choosing button prompts. In a multiplayer room they are nil in the scene script, control scripts and authority objects, so read them from a GUI or camera script, with an or "keyboard" fallback. See Which device is the player using?
Do not add your own threshold to the movement axes
moveAxisX and moveAxisY already carry the player's own dead zone and response curve by the time a script reads them. Re-gating them with something like if math.abs(input.moveAxisX) > 0.15 then tests each axis on its own, which throws away the smaller component of every diagonal: pushing forward-and-slightly-left moves the character straight forward, and fine steering on touch becomes impossible. Read the axes as given, or test their combined magnitude rather than each axis separately.
Look
Read lookDeltaX and lookDeltaY. They contain total per-frame look, already scaled by the player's sensitivity and invert settings. One delta unit is about 0.172°, so 180° is roughly 1047 units. lookAxisX/lookAxisY expose held arrow-key or look-stick deflection, but the engine already integrates that axis into the deltas; reading both applies held input twice.
A first_person or first_person_absolute camera consumes the total deltas. first_person_absolute (First Person (Absolute Aim)) keeps its yaw in world space, so a script that turns the body toward the view does not turn the camera a second time; first_person adds look to the body's rotation. A third_person boom consumes only pointer look — mouse movement or touch drag — because arrow keys and the touch look stick are intended to turn the followed character through its script; the boom then follows the character's rotation.
Four things produce look, and not all of them exist on every device:
- Arrow keys — always, on a keyboard.
- Mouse — only when the scene enables Desktop mouse look in its player controls. It is off by default, because pointer lock hides the cursor and stops DOM clicks reaching
guiButtonelements. The canvas click that captures the mouse triggers no action; later left clicks triggerprimaryFireunless an authoredMouse0binding overrides it. A mouse contributes one delta unit per CSS pixel of movement. - Touch look stick, or a drag anywhere that is not the movement stick or an action button — only on a touch device with mobile controls enabled. A touch drag is normalized against the viewport width rather than counted in pixels, so a swipe turns the same amount on a phone and on a tablet; a drag across the full width turns 320°. Vertical runs at 0.78x the horizontal rate.
- Gamepad right stick — on any gamepad the browser reports with the standard mapping. It is held look, like the arrow keys. See Gamepad.
A held stick or arrow key contributes 600 delta units per second at full deflection, or about 103° per second, and a gamepad's right stick counts as a held stick.
Actions
Authored action buttons are exposed through input.actions.<id>. Action IDs are arbitrary stable snake_case identifiers chosen in the scene's player controls configuration, so scripts can define actions such as input.actions.reload, input.actions.crouch, or input.actions.weapon_swap. The action IDs jump, primary_fire, and crouch are also mirrored to input.jump, input.primaryFire, and input.crouch. crouch is held rather than pressed, so pass it straight to setCrouched(input.crouch).
A key appears in input.actions only once that button has been pressed, so an untouched action reads nil rather than false. if input.actions.reload then is safe; comparing against false is not.
input.actionValues.<id> says how far the same action is held, from 0 to 1. A key, mouse button, touch button or digital gamepad button reads 0 or 1; a gamepad trigger bound to the action reads its pull, including a light pull too small to count as pressed in input.actions. Use it for anything proportional, such as throttle and brake on the triggers: gameObject.setDriverInput((input.actionValues.gas or 0) - (input.actionValues.brake or 0), steer, 0, 0). Like input.actions, an action that has not been touched has no entry, hence the or 0. In a multiplayer room the room server and the player's own prediction read the same values.
Each action needs a route on the devices you support. A button may name up to four desktop bindings using KeyboardEvent.code values plus Mouse0/Mouse1/Mouse2. Without authored keys, non-reserved actions fall back to Digit1 through Digit9 by author position. jump and primary_fire retain Space and left mouse as compatibility bindings but may name explicit alternatives. An action also gets a gamepad button: the one it names in gamepadButtons, or a default (see Gamepad). The current maximum is six authored actions.
The input bus is shared and singular. There is no per-player or per-device routing, and there is no API for reading arbitrary keyboard keys or mouse buttons from Lua, so multiple devices feed the same fields and authored actions. In a multiplayer room each player's input is sent to the room server, where the control script of the character or vehicle that player controls reads it as input.
Missing values
Bindings return Lua nil when nothing is found. Check a returned object before calling methods on it.
Physics calls refuse numbers that are not finite
Lua makes NaN and infinity easily — 0/0, 1/0, math.huge, or normalizing a zero-length vector. A call that would hand one to physics is skipped instead: setting a position, rotation or velocity, rotate, forces, torques and impulses, resetPhysicsState, setCharacterVelocity and the planet-gravity setters, moveKinematic, grab, moveTo, the sphere and box queries, vehicle and track inputs, constraint targets, the ragdoll bone calls, scene.setGravity, and the geometry given to scene.createObject. A rotation quaternion with no length is skipped the same way. The rest of the callback still runs, and the skip is reported as a script error named rejected and the call, such as rejected setLinearVelocity(), saying which argument was bad. moveTo then returns false, a query returns no hits, createObject, grab and startTrail return nil, and moveKinematic returns false.
Multiplayer Lua
Object and scene scripts receive a multiplayer global. In solo play multiplayer.isHost() returns true. In a multiplayer room the game is run by a room server, and every script runs in one of three places, which decides what it may call:
- Authority — the room server only: the scene script, the control script of each character or vehicle bound to a player slot or spawned from a spawn template, and scripted objects declared
"authority". Only these may change the game.isHost()is true here and nowhere else. - Presentation — every player's browser, never the room server: camera and GUI scripts, and scripted objects declared
"presentation". Only these may touch GUI, sound (filters and reverb included), lights, the active camera and its lens and follow settings, an object's visual scale, opacity and tint, trails, particle emitters, andgameStorage, or play a clip on a character. - Prediction — the controlling player's browser also replays their character's or vehicle's control script to show movement at once. A control script must therefore give the same result every time: no
os.time,os.clockoros.date, and never branch on the result offire,setController,hold,release,destroy,moveTo,followPath,spawn,despawn,setPrimary, or object creation.
A call from the wrong runtime raises an error that names it. Animation is the exception: every browser animates every character from its movement, so a control script's enableAutoAnimation and updateAutoAnimation keep working unchanged. The rest of the animation family, including the bone-socket calls such as attachToBone, quietly does nothing on the script's own object in an authority or prediction script, because the room server never poses a skeleton: attach a weapon to a hand from a presentation script, and never decide a hit from what a bone holds. Outside a room every script keeps the whole API. Editor Preview is outside a room: it plays the game as one player in the slot you choose, so onPlayerJoined never fires, shared state raises an error, sendAction returns false, "unavailable" and multiplayer.spawn returns nil, "unavailable". Test those with Test in a room on Preview's start screen, which runs your draft in a real room, or in a room on the published game.
multiplayer.sendAction(name, payload)asks the room server for an outcome, from a GUI button or a player's character or vehicle control script, and returnsok, reason. The scene script cannot send one: it is what receives them, inonPlayerAction(participant, name, payload), and it hears arrivals and departures throughonPlayerJoined(participant)andonPlayerLeft(participant). An action the room server turned away never reachesonPlayerAction; it arrives inonPlayerActionRefused(participant, name, reason)instead, which is where to count refused shots. A projectile frommultiplayer.firethat ends on something arrives inonProjectileImpact(impact)-weapon,entityId,shooterId,targetIdorhitId, andposition- after the step, with its damage already in avatar state.participantis always{id, playerSlot, choices, isBot}, wherechoicesis what the player picked in the lobby (an empty table in a game without lobby choices) andisBotis true for a bot a test room's server plays and false for a person.multiplayer.isBot(participantId)says whether a participant is a test room's bot, in any script; it isfalseoutside a room, and still true for a bot inonPlayerLeft. A bot joins, spawns and plays through the same calls as a person, so use it only to leave bots off a leaderboard or out of a count, never to give them different rules. A bot's lobby choices can change mid-game when it gives way to a person, andonPlayerLeftfires for a bot that leaves to free a seat. See "Test in a room" in Build and test a multiplayer game.- The scene script may define
onBotThink(bot, dt)to play a test room's bots added with thescriptbrain. The room server calls it for each such bot 30 times a second, onceonPlayerJoinedhas announced it, withbotthe{id, playerSlot, choices, isBot}table anddtin seconds. Return nil for no input, or a table the bot's control script then reads asinput:moveAxisX,moveAxisY,lookAxisXandlookAxisY, from -1 to 1;aimYawandaimPitchin radians, asinput.aimYawreads them. Leave them out and the bot keeps its last aim, whichlookAxisX= 1 then turns to the right;- booleans
jump,primaryFire,crouchandmoveSprint; actions = { reload = true }andactionValues = { gas = 0.5 };authorityActions = { { name = "pass", payload = { power = 0.5 } } }, up to 16 a call. Each is raised as if the bot had calledsendAction, is checked against the action schema, and reachesonPlayerActionwith the bot as the participant.
onBotThinkis reported the same way and gives the bot no input that tick. With noonBotThink, ascriptbot stands idle and the room reports it once. Keep it cheap, because it runs for every bot thirty times a second.
The same callback plays every character or vehicle whose Played by setting is Bot: Script, in solo play and, for one no player controls, on a room's server. For those,botis{id = "bot:" .. objectId, objectId, isBot = true}: look the object up withscene.getObject(bot.objectId). The return table is the same, except thatauthorityActionsare ignored and reported once. See Played by a bot. multiplayer.fire(templateId)fires a release-frozen weapon from a control script; the room server resolves the shot at once. Call it for its effect only.- If a player's avatar state holds a numeric
shield, hitscan and projectile damage drain it beforehealth, and any overflow comes off health; only health decidesalive. Nothing regenerates it for you: set and refill it from the scene script withgetAvatarStateandsetAvatarState, keeping the other keys. getGameState(),getParticipantState(id),getAvatarState(objectId), andgetPrivateState([participantId])return detached state snapshots in any script in a room. Outside a room, including editor Preview, they and the setters raise "multiplayer state requires a multiplayer room".setGameState(state),setParticipantState(id, state),setAvatarState(objectId, state), andsetPrivateState(id, state)are for authority scripts.multiplayer.getSceneRevision()counts the room's scene changes: 0 for the scene it started in and one more for eachscene.loadSceneorscene.restart. It is 0 outside a room.multiplayer.sendEvent(name, payload[, participantId])sends a declared presentation event from an authority script; presentation scripts receive it inonMultiplayerEvent(name, payload).- Presentation scripts may define
onMultiplayerStateChanged(change), called after replicated state changes. multiplayer.getPlayerSlot(objectId)returns the player slot an object is bound to, ornil; an object's multiplayer settings are not variables, and no script can change them.multiplayer.getController(objectId)and, from an authority script,multiplayer.setController(objectId, participantId)read and hand over control of a slotted or spawned character or vehicle. A player may control up to four objects, all driven by the same input; the camera follows their primary one. From an authority scriptmultiplayer.setPrimary(participantId, objectId)chooses it, and in any scriptmultiplayer.isPrimary(objectId)says whether an object is its controller's primary andmultiplayer.getControlled(participantId)lists what a player controls, primary first. Every object a player controls sees the same press, so a control script that sends an action on a press should checkmultiplayer.isPrimary(gameObject.id)first.multiplayer.getRoomOptions()returns the room’s shared lobby selection, keyed by setting name, from any room script, includinginit(). The lobby owner chooses it before Start; for example,multiplayer.getRoomOptions().terrainnames the selected terrain. The table is detached and read-only in effect: changing it does not publish anything. It returns an empty table outside a room. These settings are separate from per-player lobby choices, and stay fixed for late joins and reconnects. See “Let the lobby owner choose the map” in Build and test a multiplayer game.multiplayer.getLobbyChoices(participantId)returns what a player chose in the lobby, keyed by choice name, in any script in a room: an empty table for a player who chose nothing,nilfor someone not in the room. In a game with lobby choices,onPlayerJoinedruns once the room starts, so the choices it sees are final. See "Let players choose in the lobby" in Build and test a multiplayer game.- From an authority script,
multiplayer.spawn(template, x, y, z, options)copies a spawn template — an object whosemultiplayer.spawnTemplatesetting is on — into the room for every player and returnsid, reason;optionsmay setyaw,variables,respawnDelayMs,killHeight(each defaulting to the template's own setting) andcontroller.multiplayer.despawn(id[, { respawn = false }])removes a copy.multiplayer.getTemplate(id)andmultiplayer.getSpawnedObjects([template])read what is live in any script. The scene script hearsonObjectSpawned(object, template)andonObjectDespawned(id, template, reason, respawning). See "Spawn objects during play" in Build and test a multiplayer game. - From an authority script,
multiplayer.hold(propId, holderId, x, y, z)has a slotted character or vehicle carry an authority prop at an offset in its own frame, andmultiplayer.release(propId, vx, vy, vz)puts it back moving at that velocity — a throw, or a drop.multiplayer.getHolder(propId)names the holder or returnsnil. See Build and test a multiplayer game. - From a presentation script,
multiplayer.getPresetMessageOptions()lists the preset messages the local player may send andmultiplayer.sendPresetMessage(key)sends one, returningok, reason. Presentation scripts receive every player's message inonPresetMessage(message). See "Let players talk with preset messages" in Build and test a multiplayer game.
local wasFiring = false
function update(deltaTime)
local firing = input.primaryFire == true
if firing and not wasFiring then
multiplayer.fire("rifle")
end
wasFiring = firing
end
Multiplayer boundaries
Returned state tables are detached; changing one does not publish it. A player's browser can read only its own private state. In a room only the scene script may call scene.loadScene and scene.restart, and only the state listed in their keep option survives the change. An object made with scene.createObject or scene.cloneObject in a room exists only on the room server, and scene.setTimeScale raises an error there; copy a spawn template with multiplayer.spawn for one every player sees. If the room server is lost, the room ends. See Build and test a multiplayer game for the full rules.
What Lua a script gets
Scripts run Lua 5.4 with the standard libraries — string, table, math, os, and the rest. math.atan2 is kept as an alias of two-argument math.atan for older scripts. Each script has its own globals; one script cannot read another's variables except through getVar/setVar and the APIs above.
In single-player play and in the editor that is the whole story. On a multiplayer room's server, scripts run with limits:
io,package,require,dofile,loadfile, anddebugare removed, andoskeeps onlytime,clock,date, anddifftime.loadstill works, for source text only. Because none of this applies in the browser, a script that usesioworks in Preview and fails in a room — test multiplayer games in a room.- Any single callback —
init,update,onPlayerActionand the rest — is stopped after about one second. Code at a script's top level has no such limit, so never loop there: a loop that does not finish stalls the room, and the room is ended. - A character's or vehicle's control script gets a
math.randomseeded per room, so the predicted copy in the player's browser draws the same numbers as the server.math.randomseedonly reseeds that sequence. In a game whose scene script changes scene, the room server's other scripts get amath.randomreseeded at every change, so a restarted round does not repeat the last one's numbers.os.time,os.clock,os.date, andos.difftimeraise an error there; for elapsed time, add up thedeltaTimethatupdateis given.
Engine values are Lua tables
gameObject, scene, every object a lookup returns, and the data calls return, such as a position, a raycast hit or a multiplayer state snapshot, all reach a script as ordinary Lua tables. type() of any of them is "table", pairs lists an object's members, and both obj.getPosition() and obj:getPosition() work. Before 17 October 2026 they were "userdata", so a check such as type(state) == "table" on multiplayer.getPrivateState() never passed; it now does.
A field a script writes onto one of these stays in that script. Returned data is a copy, and input is the script's own table for the step, so input.jump = false clears the jump only for the script that wrote it. Before 17 October 2026 it cleared it for every script that ran after it in that step.
Performance. A call into the engine is several times cheaper than it was, and reading x, y and z off a returned position no longer costs anything extra. The engine keeps one table per object for each script and fetches each method once, so storing a method in a local (local setPosition = obj.setPosition) gains little. What still matters is finding objects: look each one up once in init() and keep it in a local, rather than calling getObjectByName every frame.
local ball
function init()
ball = gameObject.getObjectByName("Ball")
end
function update(deltaTime)
if ball then
local p = ball.getPosition()
gameObject.setPosition(p.x, p.y + 2, p.z)
end
end
Any lookup that hands a script an object, by name, type, name prefix, id, variable, parent or child, also takes that object out of the batched scenery drawing in Preview and published games for the rest of the play. Look up the objects a script needs by name; avoid sweeping the whole scene with getObjectsByType("cube") or a short getObjectsByNamePrefix. See "Performance: point light budget and render scale" in Editor basics.
Editor Lua is a separate world
Everything above describes Lua that is attached to an object or a scene and runs while a simulation is running. The editor also has a REPL for throwaway Lua that inspects or edits the scene you are authoring, opened with Cmd/Ctrl + Shift + L. The two do not share an API surface: REPL code gets a single editor global and has no gameObject, scene, input, or gameStorage, and nothing on this page is available there. See "Editor Lua REPL" in Editor basics.