The task library is small (wait, spawn, delay, defer, cancel), but a couple of patterns with it come up in almost every round-based game. Sharing the ones I find most useful.
Round timers you can cancel
A round usually ends one of two ways: time runs out, or someone wins early. If you implement the timer as a loop with waits, ending early means sprinkling flags everywhere. task.delay + task.cancel is cleaner:
local roundTimer = nil
local function endRound(reason)
if roundTimer then
task.cancel(roundTimer)
roundTimer = nil
end
print("Round ended: " .. reason)
-- cleanup, rewards, etc.
end
local function startRound(duration)
roundTimer = task.delay(duration, function()
roundTimer = nil -- clear first, see below
endRound("time up")
end)
end
-- somewhere in your win check:
-- endRound("winner found")
The roundTimer = nil before calling endRound from inside the delayed function matters. Cancelling the coroutine that’s currently running raises a cannot cancel thread error, so you don’t want endRound trying to cancel the thread it’s running in.
task.cancel also works on threads suspended in task.wait, and a cancelled thread never resumes. Handy for countdown loops too.
task.wait tells you how long it actually waited
task.wait(1) returns the real elapsed time, which won’t be exactly 1. If you’re accumulating time (survival timers, score per second), add the returned value instead of assuming 1:
local survived = 0
while alive do
survived = survived + task.wait(1)
end
Background loops in task.spawn
A while true do ... end at the top level of a script blocks everything below it. Wrap long-running loops (autosave, spawners, day/night) in task.spawn so the rest of the script still runs:
task.spawn(function()
while true do
task.wait(60)
autosaveAll()
end
end)
task.spawn also takes arguments directly, so task.spawn(handleHit, player, damage) works without wrapping it in an anonymous function.
task.defer for “after this finishes”
task.defer runs a function once the current coroutine finishes. Useful when you want something to happen right after the current handler is done rather than in the middle of it.
Source: Conveniently Managing Coroutine Using Task
How are people handling round state in general? Plain functions like this, or a full state machine module? Curious where people draw the line.