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.

Concept lesson, about 80 minutes, 12 steps

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

1A 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.

Figure 1.1.

A playtest: walking onto a pad collects the coin, and the server spawns a new one about four seconds later.

Transcript
  1. 0:05 Play is running. A coin is on the pad.
  2. 0:08 The touch collected the coin. The pad is empty.
  3. 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)
Figure 1.2

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?

Answer

14 seconds (within 0.1). task.delay(4, ...) runs the spawn function about 4 seconds later, at about 14 seconds. It resumes on the first frame after the time is up, so it can be a few milliseconds late, never early.

Open this step in lesson mode · Link to this step · This confused me

2Events: 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.

Both sidesAn event and :Connect is a doorbell.
In the pictureIn Roblox
Wiring the bell to a chimeevent:Connect(handler)
Someone pressing the buttonThe engine firing the event
Not checking the door every secondNot polling in a loop

See the whole analogy cast

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.

Luau with roblox-lite (not Roblox)
local touched = Signal.new()
local connection = touched:Connect(function(partName)
	print("touched by", partName)
end)
touched:Fire("LeftFoot")
touched:Fire("RightFoot")
connection:Disconnect()
touched:Fire("LeftHand")
print("connected?", connection.Connected)
Figure 2.1. Expected output: touched by LeftFoot touched by RightFoot connected? false

Open this step in lesson mode · Link to this step · This confused me

3Connections 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.

Luau with roblox-lite (not Roblox)
local roundEnded = Signal.new()
roundEnded:Once(function(winner)
	print("first round won by", winner)
end)
roundEnded:Fire("Ava")
roundEnded:Fire("Ben")
local count = 0
local heartbeat = Signal.new()
for round = 1, 3 do
	heartbeat:Connect(function()
		count += 1
	end)
end
heartbeat:Fire()
print("handlers ran", count)
Figure 3.1. Expected output: first round won by Ava handlers ran 3

In the cell above, a new Heartbeat handler is connected every round and never disconnected. After 50 rounds, what happens on each frame?

  1. 50 handlers run every frame, and the game slowly gets heavier
  2. Only the newest handler runs
  3. Roblox removes old handlers automatically at the end of a round
  4. The script errors at the second Connect
Answer

50 handlers run every frame, and the game slowly gets heavier. Each Connect adds another handler. Nothing removes them, so every frame runs all 50. Keep the connection and Disconnect it when the round ends.

Open this step in lesson mode · Link to this step · This confused me

4What 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.

Luau
local function makeCounter(name)
	local count = 0
	return function()
		count += 1
		print(name, count)
	end
end
local pad1 = makeCounter("Pad1")
local pad2 = makeCounter("Pad2")
pad1()
pad1()
pad2()
local later = {}
for index = 1, 3 do
	table.insert(later, function()
		return index
	end)
end
print(later[1](), later[3]())
Figure 4.1. Expected output: Pad1 1 Pad1 2 Pad2 1 1 3

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())
  1. pay skip pay
  2. pay skip skip
  3. pay pay pay
  4. skip skip skip
Answer

pay skip pay. Each makeCoin call creates its own claimed. coinA pays once and then skips; coinB has a fresh flag and pays.

Open this step in lesson mode · Link to this step · This confused me

5task.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.

Both sidestask.wait is set a timer and nap.
In the pictureIn Roblox
Setting the timertask.wait(seconds)
Napping while others workThe thread yields; other scripts keep running
Waking upThe scheduler resumes the thread

See the whole analogy cast

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.

Luau with roblox-lite (not Roblox)
local start = time()
task.delay(4, function()
	print(string.format("coin respawns at %.1f s", time() - start))
end)
print("collected at 0.0 s")
task.wait(2)
print(string.format("still waiting at %.1f s", time() - start))
task.wait(3)
print("done")
Figure 5.1. Expected output: collected at 0.0 s still waiting at 2.0 s coin respawns at 4.0 s done
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?

  1. It is at least 0.01 s (usually ~0.0167 s), because task.wait wakes on the next frame boundary, never early
  2. It is always exactly 0.0100 s
  3. It pauses every other script on the server for 0.01 s
  4. It returns nil
Answer

It is at least 0.01 s (usually ~0.0167 s), because task.wait wakes on the next frame boundary, never early. task.wait yields only the calling thread and resumes on the first Heartbeat at or after the requested duration, returning the real elapsed time.

Open this step in lesson mode · Link to this step · This confused me

6Run it now, or right after: spawn and defer

Two more calls start a function as a new thread3:

  • task.spawn(fn) runs fn immediately, until it finishes or yields, then the caller carries on.
  • task.defer(fn) waits until the current work finishes, then runs fn on the same frame.
Both sidestask.spawn is hand a job to a helper.
In the pictureIn Roblox
Handing over the jobtask.spawn(fn)
The helper starting at oncefn runs immediately until it yields
You carrying onThe caller continues after fn yields or ends

See the whole analogy cast

Both sidesRemember: task.spawn is hand a job to a helper.

Luau with roblox-lite (not Roblox)
local order = {}
task.defer(function()
	table.insert(order, "defer")
	print(table.concat(order, ","))
end)
task.spawn(function()
	table.insert(order, "spawn")
end)
table.insert(order, "now")
Figure 6.1. Expected output: spawn,now,defer
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.

  1. A
  2. C
  3. D
  4. B
Answer

1. A 2. B 3. D 4. C. spawn prints A and then yields at task.wait. The caller prints B. The deferred function runs as soon as the current work finishes, printing D. One second later the spawned thread wakes and prints C.

You call task.spawn(function() while true do end end) with no task.wait inside. What happens to the line right after task.spawn?

  1. It cannot run while the spawned loop continues without yielding
  2. It runs in parallel on a second CPU core
  3. It runs first, and the loop starts next frame
  4. Luau inserts a task.wait automatically
Answer

It cannot run while the spawned loop continues without yielding. task.spawn is cooperative single-threaded concurrency. It runs the new coroutine immediately until it finishes or yields, so the caller cannot continue while the loop runs without yielding.

Open this step in lesson mode · Link to this step · This confused me

7Every 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.

Luau
local SPEED = 12
 
local function simulateOneSecond(fps)
	local x = 0
	local dt = 1 / fps
	for _frame = 1, fps do
		x += SPEED * dt
	end
	return x
end
 
print(string.format("60 FPS: %.2f studs", simulateOneSecond(60)))
print(string.format("20 FPS: %.2f studs", simulateOneSecond(20)))
Figure 7.1. Expected output: 60 FPS: 12.00 studs 20 FPS: 12.00 studs

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?

Answer

0.6 studs (within 0.001). 12 × 0.05 = 0.6 studs. On a normal 1/60 s frame it would be 0.2 studs; multiplying by dt keeps the real-world speed steady.

Open this step in lesson mode · Link to this step · This confused me

8Deferred 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:

Luau with roblox-lite (not Roblox)
local pad = Instance.new("Part")
pad.Name = "Pad1"
local seenChange = false
pad:GetAttributeChangedSignal("PadIndex"):Connect(function()
	seenChange = true
end)
pad:SetAttribute("PadIndex", 1)
print("next line", seenChange)
task.wait()
print("after a yield", seenChange)
Figure 8.1. Expected output: next line false after a yield true

Open this step in lesson mode · Link to this step · This confused me

9Where 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?

  1. Touched fires for every body part that touches, many times per visit, so the handler must ignore repeats itself
  2. Touched fires only once, but on two threads
  3. seen stores coins for saving
  4. claimed is only for the test suite
Answer

Touched fires for every body part that touches, many times per visit, so the handler must ignore repeats itself. One visit rings the bell many times: every foot and leg part that starts touching fires Touched. The handler's own guards turn that burst into one payout.

Open this step in lesson mode · Link to this step · This confused me

10Build 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

OptionWhat it isWhen pros pick itTrade-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.
BindableEventA 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 libraryroblox-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.
Luau with roblox-lite (not Roblox)
local function newBag()
	local items = {}
	return {
		add = function(_, item)
			table.insert(items, item)
			return item
		end,
		clean = function(_)
			for i = #items, 1, -1 do
				local item = items[i]
				items[i] = nil
				if typeof(item) == "function" then
					item()
				elseif item.Disconnect then
					item:Disconnect()
				end
			end
		end,
	}
end
 
local heartbeat = Signal.new()
local count = 0
local bag = newBag()
local conn = bag:add(heartbeat:Connect(function()
	count += 1
end))
bag:add(function()
	print("round state cleared")
end)
 
heartbeat:Fire()
bag:clean()
heartbeat:Fire()
print("count", count, "connected?", conn.Connected)
Figure 10.1. Expected output: round state cleared count 1 connected? false

Build along

m03-coins-count

  • src/shared/Config.luau
  1. Run git checkout m03-coins-count with rojo serve running.

    You should see git checkout reports you are at m03-coins-count, and Config.luau has COIN_RESPAWN_SECONDS = 4.

  2. In src/shared/Config.luau, change COIN_RESPAWN_SECONDS from 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.

  3. 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.

Open this step in lesson mode · Link to this step · This confused me

11Challenges

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

Hints

  1. Search each file for task.
  2. Four seconds is a timer, not 'right after this'.
Solution
luau
-- CoinService: task.delay (the respawn timer)
-- RoundService: task.spawn (the round runs while requestStart returns)
-- DataService: task.defer (after the CharacterAdded callback finishes)

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 in the lesson view; 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

Hints

  1. Read local now = time() and check if lastSwing ~= nil and now - lastSwing < SWING_GAP then return false end.
  2. Update lastSwing = now only when the swing is allowed.
Solution
luau
local SWING_GAP = 0.4
local lastSwing = nil
local function onSwing()
	local now = time()
	if lastSwing ~= nil and now - lastSwing < SWING_GAP then
		return false
	end
	lastSwing = now
	return true
end
Luau with roblox-lite (not Roblox)
-- Write onSwing(): it returns true if at least 0.4 s of game time passed
-- since the last allowed swing, and false otherwise. Use time().
local SWING_GAP = 0.4
local lastSwing = nil
local function onSwing()
	return true
end
Figure 11.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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 run game.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

Hints

  1. Copy the scheduler-order cell, but write the attribute instead of printing.
  2. Write the attribute inside the deferred function, so the string already contains defer.
  3. Do not task.wait between the three lines.

Open this step in lesson mode · Link to this step · This confused me

12Recap

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

  1. 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.
  2. A handler is a closure: it keeps the locals it was made with, which is how each coin has its own seen set.
  3. 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.

Next Debugging basics: Output, stack traces and breakpoints

Open this step in lesson mode · Link to this step · This confused me