Overview
Script lifecycle
How a script starts, what runs every frame, and in what order.
Starting a script
When a script is launched, the client compiles it against the sandbox environment and starts it with task.spawn. This means:
- The main chunk runs inside a coroutine. You can call
task.wait()at the top level. - A runtime error inside any coroutine is printed to the console as an error (level 2) and stops only that coroutine.
- A script that finishes its main chunk keeps working if it left signal connections or scheduled threads behind.
What happens every frame
The host calls the scheduler once per rendered frame with the frame time dt. In order:
- Connection state is checked (this is what fires
mc.Events.Connected,DisconnectedandServerChanged). - Network events are pumped (this is what fires
rnethandlers). - The scheduler clock advances by
dt. - Threads whose
task.waithas finished are resumed. - Threads queued with
task.deferare resumed. - Key and mouse events are read and
InputBegan/InputEndedare fired. Steppedfires with(time, dt).Tickfires at a fixed 20 Hz, up to 5 times in one frame to catch up.Heartbeatfires withdt.RenderSteppedfires withdt.
See Scheduler for each of these.
Two clocks
- The scheduler clock advances by the frame time and drives
task.wait,task.delayandtime()-style timing inside the scheduler. os.clock()and theTimehelpers use the process clock.
Both increase steadily during normal play. Use the one the API you are calling expects: task.wait returns scheduler time.
Limits
Scripts run with a memory limit and a per-frame time limit. A script that goes over is stopped. The Drawing library allows at most 2000 live objects.