Skip to content

Lesson 5 of 9 · 25m

Coroutines, Events, and Frame-Time Discipline

Model scripted sequencing with Lua coroutines and event subscriptions while respecting cooperative execution, cleanup, and frame budget constraints.

The most common coroutine misunderstanding is architectural: developers see yield and assume they have threads. They do not. Lua coroutines are cooperative control-flow objects. They are wonderful for cutscenes, ability channels, tutorials, scripted encounters, and retry logic — until one forgets to yield, one resumes after its owner dies, or an event handler keeps the entire object graph alive. In games, time is the scarce resource.

Coroutines are scripts over time

A coroutine expresses sequencing without turning every step into a callback:

local co = coroutine.create(function(ctx)
    ctx.ui:show("The gate is opening")
    coroutine.yield("wait", 1.5)
    ctx.world:open_gate("north")
end)

local ok, command, seconds = coroutine.resume(co, ctx)
if ok and command == "wait" then
    scheduler:after(seconds, function() coroutine.resume(co) end)
end

The coroutine is not running while suspended. The scheduler owns when it resumes; that separation is the design.

A dead owner invalidates the sequence

When an encounter resets, a player dies, or a map unloads, outstanding coroutines must stop:

function sequence:cancel() self.cancelled = true end
local function step(self)
    if not self.cancelled then coroutine.resume(self.co, self.ctx) end
end

Garbage collection is not game logic. Without cancellation, work from one attempt can fire inside the next.

Events need lifetimes too

Subscriptions are memory ownership edges:

local conn = bus:on("player_damaged", handler)
function panel:destroy() conn:disconnect() end

In Roblox, RBXScriptConnection:Disconnect() plays the same role. Handlers that close over dead UI or entities otherwise keep object graphs alive.

Respect the frame budget

Lua often shares the frame with rendering, physics, animation, networking, and input. Unbounded scans such as this can consume the budget:

for _, enemy in ipairs(enemies) do
    if enemy:distance_to(player) < aggro_radius then enemy:chase(player) end
end

Use spatial partitioning, dirty flags, events, lower-frequency schedulers, or native engine queries. Frequency and data structure matter before syntax.

Field notes

  • Coroutines do not create parallelism; they only reshape control flow.
  • Cancellation and cleanup are part of the sequence contract, not optional polish.
  • Every event subscription needs an owner and a disconnect path.
  • Frame-time problems are usually frequency and data-structure problems; ignored coroutine.resume errors silently kill sequences.

Was this lesson helpful?

Sign in to rate