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:

  1. Connection state is checked (this is what fires mc.Events.Connected, Disconnected and ServerChanged).
  2. Network events are pumped (this is what fires rnet handlers).
  3. The scheduler clock advances by dt.
  4. Threads whose task.wait has finished are resumed.
  5. Threads queued with task.defer are resumed.
  6. Key and mouse events are read and InputBegan / InputEnded are fired.
  7. Stepped fires with (time, dt).
  8. Tick fires at a fixed 20 Hz, up to 5 times in one frame to catch up.
  9. Heartbeat fires with dt.
  10. RenderStepped fires with dt.

See Scheduler for each of these.

Two clocks

  • The scheduler clock advances by the frame time and drives task.wait, task.delay and time()-style timing inside the scheduler.
  • os.clock() and the Time helpers 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.