Lesson 3 of 6
Events, signals and the task library
Learn Roblox events and the task library in Luau. Connect and Disconnect, closures, task.wait, task.spawn, task.defer, task.delay, Heartbeat and deferred events, run in the browser and traced through Beacon Yard's coin respawn.
By the end you can
- Connect a function to an event, disconnect it, and explain what a closure keeps alive
- Choose between task.wait, task.delay, task.spawn and task.defer, and predict the order they run in
- Move something smoothly with Heartbeat's frame time instead of a polling loop
Before this: ModuleScripts and require
Step 1 of 12
A coin that comes back by itself
Collect a coin at m03-coins-count and the pad stays empty for a moment. About four seconds later a new coin appears. No loop is watching the clock. When the coin is touched, CoinService asks the engine to call a function four seconds from now, and goes back to doing nothing.
A playtest: walking onto a pad collects the coin, and the server spawns a new one about four seconds later.
Transcript
- 0:05 Play is running. A coin is on the pad.
- 0:08 The touch collected the coin. The pad is empty.
- 0:11 About four seconds later the coin is back. That wait is task.delay.
task.delay(delaySeconds, function()
if pad.Parent then
spawnCoin(pad)
end
end)
Config.COIN_RESPAWN_SECONDS is 4. A player collects a coin at 10.0 seconds into the game. At about what time does the new coin appear?
Step 2 of 12
Events: let the engine call you
Roblox objects announce things through events: a part's Touched, Players.PlayerAdded, a button's Activated. You give an event a function with :Connect(fn). The engine calls that function every time the event fires, passing details as arguments: Touched passes the part that touched1.
| In the picture | In Roblox |
|---|---|
| Wiring the bell to a chime | event:Connect(handler) |
| Someone pressing the button | The engine firing the event |
| Not checking the door every second | Not polling in a loop |
An event is a doorbell. You do not stand at the door checking every second; you wire the bell to a function and get on with your day.
Think of it as A doorbell
The browser runner has no parts, so it offers Signal.new(), a stand-in for the events you will use in Studio. It is Luau, not Roblox, but Connect, Fire and Disconnect behave the same way.
Step 3 of 12
Connections are handles: keep them, drop them
:Connect returns a connectionConnectionThe handle :Connect returns. Call :Disconnect() on it to stop the calls.Think of it as the wire between a doorbell and the chime; cut it and the chime stops.. Call :Disconnect() on it when you no longer want the calls. :Once(fn) connects a function that disconnects itself after the first fire.
When an instance is destroyed, Roblox disconnects every connection on its own events. That is why CoinService never disconnects a coin's Touched: coin:Destroy() does it, and the respawned coin gets a fresh connection. A connection on something that lives forever, such as Players.PlayerAdded or RunService.Heartbeat, stays until you disconnect it. Connecting one inside a loop or per round, without disconnecting, is the classic memory leak.
In the cell above, a new Heartbeat handler is connected every round and never disconnected. After 50 rounds, what happens on each frame?
Press 1 to 4 to choose, Enter to check.
Step 4 of 12
What a handler remembers
The function you pass to Connect is usually written right there, inside another function. It can use that outer function's locals, and they stay alive as long as the handler does. A function that keeps its surrounding locals is a closureClosureA function that keeps using the local variables that were in scope where it was created.Think of it as a backpack of variables a function carries with it..
CoinService's Touched handler is a closure. It keeps the coin, the pad, the claimed flag and the seen set that spawnCoin created, long after spawnCoin has returned. Each coin's handler has its own set, because each call to spawnCoin made new locals.
In a Luau for loop, each pass also gets a fresh loop variable, so a closure made on pass 1 still sees 1.
What does this print?
local function makeCoin()
local claimed = false
return function()
if claimed then return "skip" end
claimed = true
return "pay"
end
end
local coinA = makeCoin()
local coinB = makeCoin()
print(coinA(), coinA(), coinB())
Press 1 to 4 to choose, Enter to check.
Step 5 of 12
task.wait: set a timer and nap
task.wait(seconds) pauses the current thread, and only it, for at least that long. Other scripts keep running in the meantime. Pausing like this is called yieldingYieldTo pause the current thread so the engine can run other work, then resume it later.Think of it as setting a timer and taking a nap while the rest of the house carries on.. task.delay(seconds, fn) is the same idea without pausing you: it schedules fn to run later and returns straight away2.
| In the picture | In Roblox |
|---|---|
| Setting the timer | task.wait(seconds) |
| Napping while others work | The thread yields; other scripts keep running |
| Waking up | The scheduler resumes the thread |
The runner below advances a virtual clock in fixed 1/60-second steps. That is why task.wait(4) finishes instantly and time() shows that 4 virtual seconds passed. In Roblox, Heartbeat reports the elapsed time since the previous frame.
Both sidesRemember: task.wait is set a timer and nap.
Where does it break?“Set a timer and nap” is a good picture of task.wait. Where does it stop being true?
It breaks here. The timer only rings at frame boundaries: the thread wakes on the first Heartbeat after the time is up, so it is never early and can be up to a frame late.
The true model. task.wait yields the current thread and resumes it on the first Heartbeat at or after the requested time, returning the time actually elapsed. Nothing runs in parallel; threads take turns on one scheduler.
A script calls local elapsed = task.wait(0.01) on a 60 FPS server (one frame every ~0.0167 s). What is true about elapsed?
Press 1 to 4 to choose, Enter to check.
Step 6 of 12
Run it now, or right after: spawn and defer
Two more calls start a function as a new thread3:
task.spawn(fn)runsfnimmediately, until it finishes or yields, then the caller carries on.task.defer(fn)waits until the current work finishes, then runsfnon the same frame.
| In the picture | In Roblox |
|---|---|
| Handing over the job | task.spawn(fn) |
| The helper starting at once | fn runs immediately until it yields |
| You carrying on | The caller continues after fn yields or ends |
Both sidesRemember: task.spawn is hand a job to a helper.
Where does it break?“Hand a job to a helper” is a good picture of task.spawn. Where does it stop being true?
It breaks here. Helpers take turns rather than working at the same time: a spawned function that never yields blocks the caller and every other script.
The true model. task.spawn creates a coroutine and resumes it right away on the same scheduler. Concurrency is cooperative: work interleaves only at yields such as task.wait.
This runs: task.spawn(function() print("A") task.wait(1) print("C") end) print("B") task.defer(function() print("D") end). Put the printed lines in order.
- A
- C
- D
- B
You call task.spawn(function() while true do end end) with no task.wait inside. What happens to the line right after task.spawn?
Press 1 to 4 to choose, Enter to check.
Step 7 of 12
Every frame: Heartbeat and the frame time
Some things really do change every frame, such as a moving target or enemy. For per-frame motion, connect to RunService.Heartbeat, an event that fires once per frame and passes dt, the seconds since the last frame. Multiplying speed * dt gives the distance for this frame, so an object moving at 12 studs per second travels the same 12 studs in one second whether the server runs at 60 frames per second or 20.
A while true do loop that checks something every pass is polling. It must contain a task.wait, or it never yields and the whole server freezes. Use an event where one exists, and a task.wait loop only for coarse jobs like refreshing a timer display every 0.1 seconds.
A mover has speed 12 studs per second. One slow frame has dt = 0.05 seconds. How far does it move on that frame?
Step 8 of 12
Deferred events: the handler runs a moment later
With deferred events, a handler does not run the instant its event fires; it runs at the next point where the engine resumes scripts, still within the same frame. Workspace.SignalBehavior picks the mode. Places made from Studio's templates are set to Deferred. The Default setting still behaves as Immediate today, and Roblox says it will switch to Deferred4. Beacon Yard's project file does not set it, so write handlers that work either way: never read, on the next line after firing, a flag that a handler is supposed to set.
The runner's instances always defer, like a template place. Here an attribute-changed event shows the difference:
Step 9 of 12
Where the doorbell breaks
Both sidesRemember: An event and :Connect is a doorbell.
A real doorbell rings once per press, and you hear rings in the order people pressed. Events give you neither promise.
Where does it break?“A doorbell” is a good picture of an event and :connect. Where does it stop being true?
It breaks here. One visit can ring many times (Touched fires per body part), handlers have no promised order, and a chime you never unwire keeps ringing: connections leak until you disconnect them.
The true model. An RBXScriptSignal calls every connected handler each time it fires, possibly deferred to the next resumption point. Handlers must tolerate repeats and must be disconnected when their owner goes away.
Why does CoinService need both claimed and seen, when a player only steps on a pad once?
Press 1 to 4 to choose, Enter to check.
Step 10 of 12
Build it: make the respawn obvious
There is more than one way to fire and wait on things in Roblox code. Here is what you will meet.
Signals and async tools
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Engine events (RBXScriptSignal) | Touched, PlayerAdded, Heartbeat and every other built-in event. | Always, for engine happenings. | You cannot create your own; deferred or immediate depending on Workspace.SignalBehavior. |
| BindableEvent | A built-in instance you create and Fire yourself, on one side only. | Simple custom events that must be visible in Explorer. | Arguments are copied, so tables lose identity and metatables. |
| Signal module (GoodSignal and others) | A pure-Luau signal class, like the runner's Signal. | Most studios, for events between their own modules. | Handlers run immediately, not deferred; one more dependency. |
| Promise library | roblox-lua-promise: values that resolve later, with chaining and cancellation. | Teams with many chained async steps, such as loading data, then teleporting. | A whole style to learn; plain task calls are enough for most game code. |
Build along
src/shared/Config.luau
Run
git checkout m03-coins-countwithrojo serverunning.You should see git checkout reports you are at m03-coins-count, and Config.luau has COIN_RESPAWN_SECONDS = 4.
In
src/shared/Config.luau, changeCOIN_RESPAWN_SECONDSfrom 4 to 2. Save, press Play, and collect a coin.You should see After a pickup the pad is empty for about 2 seconds, then a new coin appears.
Stop and restore the file with
git checkout -- src/shared/Config.luau.You should see git status shows a clean working tree and the respawn is 4 seconds again.
Step 11 of 12
Challenges
Level 1, Apprentice
Challenge
On m06-drone-wrench, label three real calls in the server code as spawn, defer or delay.
- Start from
- The game at milestone m06 (download)
Done means
- You name the task call CoinService uses for the respawn
- You name the task call RoundService uses to run the drill
- You name the task call DataService uses for applySpeed on a new character
Meet the criteria above, then record your own result. No test grades this check.
Level 2, Builder
Challenge
Implement onSwing() in the cell below using time(). Passing all five assertions completes this challenge.
- Start from
- The Run cell below
- Check it here
- Run the code cell; the challenge completes when it passes. No Studio needed.
Done means
- The first call to onSwing() returns true
- Calls sooner than 0.4 s later return false without resetting the timer
- A call at or after 0.4 s returns true and restarts the cooldown
Level 3, Professional
Challenge
Switch to m06-drone-wrench (where challenges/events-and-tasks.luau lives) and prove the scheduler order on the live server. The written solution is challenges/solutions/events-and-tasks.md in the game repo.
- Start from
- The game at milestone m06 (download)
- Grade it
- To grade work from an earlier milestone, apply your challenge changes to a checkout based on
m14-ship, which includes the Course Runner. In Studio, press Play, then rungame.ServerScriptService.RunGameTests:Invoke("events-and-tasks")in the server command bar. Copy the pass code from Output.
Done means
- After PolicyProbe.start() in init.server.luau, the three-line scheduler probe records spawn, now and defer
- The deferred function writes workspace attribute SchedulerOrder
- The Course Runner prints TEST PASS events_scheduler_order and a pass code
Step 12 of 12
Recap
Go deeper Coroutines, the machinery under task
Every task is a coroutine: a function that can pause in the middle and resume later. coroutine.wrap and coroutine.yield expose that directly, and you will see them in older code and in generators. In game code, prefer task.spawn and task.defer, which hand the coroutine to Roblox's scheduler for you.
Retiring the analogy
You no longer need “set a timer and nap”. task.wait yields the current thread and resumes it on the first Heartbeat at or after the requested time, returning the time actually elapsed. Nothing runs in parallel; threads take turns on one scheduler.
Recap
- Connect a function to an event and the engine calls it; keep the connection and Disconnect it when you are done, or handlers pile up.
- A handler is a closure: it keeps the locals it was made with, which is how each coin has its own seen set.
- task.wait and task.delay wake on the first frame boundary after the requested time; task.spawn runs immediately and cooperatively on one scheduler; task.defer runs right after the current work. Heartbeat's dt keeps motion steady.
An event and :Connect is a doorbell, until one visit can ring many times (Touched fires per body part), handlers have no promised order, and a chime you never unwire keeps ringing: connections leak until you disconnect them.
task.wait is set a timer and nap, until the timer only rings at frame boundaries: the thread wakes on the first Heartbeat after the time is up, so it is never early and can be up to a frame late.
task.spawn is hand a job to a helper, until helpers take turns rather than working at the same time: a spawned function that never yields blocks the caller and every other script.
Queued for review
- In the cell above, a new Heartbeat handler is connected every round and never disconnected. After 50 rounds, what happens on each frame?
- What does this print?
- A script calls local elapsed = task.wait(0.01) on a 60 FPS server (one frame every ~0.0167 s). What is true about elapsed?
- You call task.spawn(function() while true do end end) with no task.wait inside. What happens to the line right after task.spawn?
- A mover has speed 12 studs per second. One slow frame has dt = 0.05 seconds. How far does it move on that frame?
- Why does CoinService need both claimed and seen, when a player only steps on a pad once?