Scripts, sessions and saving¶
This page follows a game server from start to shutdown: when scripts start and stop, what happens when they fail or run too long, how a saved script reloads while the game runs, and how to keep player data between sessions. Entities covers creating and destroying entities, The simulation tick and physics covers what runs in each frame, and Server and clients covers players and their characters.
A server session¶
- The server loads the live version of the place. A server keeps that version until it shuts down; see Publish a place.
- Server scripts start. Autorun scripts start in sorted path order, and every script attached to an entity runs its top level once.
- A player joins. The server adds a player entity with a
Usercomponent, andComponent.User.Addedfires on the server; see Joins. On the player's machine, client scripts start once the place has loaded. - The server runs 60 ticks a second. Each tick runs physics,
Updateand the other callbacks in a fixed order; see The simulation tick and physics. - A player leaves. The server destroys the player's character, runs the server's
Component.User.Removedhandlers while the player entity still exists, and then destroys the player entity. Each client does the same with its ownUser.Removedhandlers when it removes that player. - The server shuts down. Every player leaves, so every server
User.Removedhandler runs, and the server keeps ticking for up to 30 seconds while theCloudStorerequests that scripts sent wait for their results.
How a script starts¶
A script attached to an entity starts at the beginning of the first tick after the entity appears, whether the entity was in the place file or a script made it with Clone or Prefabs.Spawn. Starting has these steps:
- The engine compiles the file. A syntax error shows a
load errorin Output, and the script does not run. - The script gets its own global variables, with
selfset to its entity. - The top level of the file runs until it returns or first waits. An error there shows an
init errorin Output, and the script does not run. - The engine looks up the global functions
UpdateandPhysicsUpdate. A function defined after the first wait never runs, and Output says so.
The top level is the place to connect signals, open stores, build queries and find the entities the script needs. A script that failed to start runs again when you fix and save it.
How a script stops¶
A script stops when its entity or an ancestor is destroyed, or when a reload replaces it. Stopping ends every signal connection the script made, its queries, its systems and the threads it scheduled with task, so a script does not need to clean up before its entity goes away. A coroutine that the script started some other way and that is still waiting fails at its next engine call with cannot run coroutine from a retired script; restart the coroutine. Disconnect ends a connection earlier.
Budgets and errors¶
Each time the engine calls into a script, such as Update, PhysicsUpdate, a system, the top level or a signal handler, that run may make 1,000,000 loop iterations and calls. A run past that stops with script exceeded its instruction budget, and wrapping the loop in pcall does not let it continue. A function that task.spawn starts shares the budget of the run that started it. Code that resumes after task.wait, task.defer or task.delay gets a fresh budget, so split long work with task.wait.
All server scripts share one memory limit of 256 MiB, and the client scripts of each player share another. Going past it raises not enough memory.
An error ends the call it happens in, and nothing else: Update runs again on the next tick, and the script's other handlers and tasks keep running. After 5 runs in a row over its instruction or memory budget, Output shows '<script path>' disabled after 5 consecutive runs over its instruction or memory budget, and the engine stops calling the script's Update, PhysicsUpdate and systems until you save the script again. A run that finishes within the budget resets the count.
Output shows the first 10 errors of one script file in 5 seconds and counts the rest. Engine errors lists every error message.
Reload a running script¶
While the place runs in Studio, saving a script reloads it in place. A file that an external editor changes reloads the same way. The world stays as it is: entities, their components and _G keep their values.
A reload runs in two steps:
- The new version compiles and runs its top level as a trial, while the old version keeps running.
- If every file in the save passes, the new version replaces the old one and Output shows a line that starts with
'<path>' reloaded. If any file fails, every old version keeps running and Output shows'<path>' reload rolled back: <phase>.
The old version's global and local variables are gone after a reload, and so are the threads it scheduled with task. To keep a value across reloads, store it in _G, which keeps its values when a script reloads, or in a component on an entity:
-- Server script in a part: count touches, and keep the count when you save the script during Play.
local touches = _G.LavaTouches or { count = 0 }
_G.LavaTouches = touches
self:On(Component.Collider.Touched, function()
touches.count += 1
print("touched " .. touches.count .. " times")
end)
Every server script reads and writes the same _G, so give each value a name that no other script uses.
To write scripts that reload:
- Keep writes to the world out of the top level. During a trial, every property write and every engine call that changes the world raise
reload: script '<path>' cannot write to the world at load (<what>); move the write into Update or an event handler, and the reload rolls back. The next Play runs the saved file either way. - Waiting is allowed. The trial runs the top level up to its first wait, so code after a top-level wait runs again on every reload.
- A connection that the new version makes to the same signal of the same entity replaces the old connection in its place. Old connections that the new version does not make again are released.
A reload also restarts a script that stopped after 5 runs over budget or that failed to start. Each player's machine reloads its client scripts on its own. A reload cannot change the fields of a component that World.DefineComponent already declared: the trial fails with <name>: this declaration does not match the registered layout of <id>, and the new fields take effect on the next Play.
Save player data¶
Entities and script variables last only as long as the server. To keep data between sessions, a server script saves it in a store:
Storesaves values by key for every place of the same owner.Getreads from memory andSetsaves in the background, so both return at once. Servers that run at the same time do not see each other's changes.CloudStoresaves values where every server of the place can read them and resolves conflicts between servers. Each method waits until the cloud answers and returns a status first.
Player data belongs in a CloudStore, keyed by the player's user ID, User.Id. Load it when the player joins and save it when they leave:
-- Server script scripts/autorun/PlayerData.server.luau
local profiles = CloudStore.Open("profiles")
local gold: { [Entity]: number } = {}
Component.User.Added:Connect(function(player: Entity)
local user = player.User
if not user then
return
end
local key = tostring(user.Id)
local status, data = profiles:Get(key)
if status ~= "Ok" then
warn("could not load " .. key .. ": " .. status)
return
end
if not player:IsAlive() then
return
end
gold[player] = if type(data) == "table" then (data :: { gold: number }).gold else 0
end)
Component.User.Removed:Connect(function(player: Entity)
local amount = gold[player]
gold[player] = nil
local user = player.User
if amount == nil or not user then
return
end
local key = tostring(user.Id)
local status = profiles:Set(key, { gold = amount })
if status ~= "Ok" then
warn("could not save " .. key .. ": " .. status)
end
end)
Get waits for the cloud, so the player may leave before it returns, and the rest of the game must cope with a player whose gold is not loaded yet. On the server, a User.Removed handler runs while the player entity still exists, so it can read player.User and player.Name. The server destroys the player entity once the handlers return or first wait, so read what you need before a call that waits, such as Set. The script saves only players whose data loaded, so a failed load never overwrites a saved profile with the defaults.
Saving only on leave loses the changes since the last save if the server stops without warning. Save important changes, such as a purchase, when they happen with Update: it runs your function on the newest record and runs it again, up to 3 times, if another server wrote the key in between.
A local test server, such as a Studio playtest, keeps cloud records in memory, so they last only until the test stops. A server can have at most 30 CloudStore requests waiting for the cloud at once. CloudStore lists the request budget and size limits, and Store lists where store files are kept.