Is there a way to write whole game codebases without the use of arbitrary waits?

Your game may be modularized enough for you to not use wait, but sometimes you need to do expensive tasks and you wouldn’t like for it to hang the player, such as generating terrain. Your goal in that example would be to yield before tasks such as rendering are skipped too much. A round-based game certainly would use wait(roundTime) somewhere, because it would be the most effective way to do it, here’s a code that would do the same but busy wait:

local function busyWait(n)
	local t = tick()
	repeat until tick() - t > n
end

Doesn’t use wait, but nobody should really do it.

You may not want to use wait but you cannot run away from the roblox thread scheduler, wait is essentially telling it: “I’m yielding, wake me up after n seconds”, which is useful for games where there isn’t necessarily an event telling when the game should end, you are responsible for that. wait is efficient in that case and allows your thread to be scheduled according to the time you called it with, and so the thread manager can resume other threads (such as rendering) and do it’s job.

Here's a few things the thread scheduler is running on my studio right now.

wait yields the same way coroutines and events do:

local thread = coroutine.running()
delay(0, function()
	coroutine.resume(thread, "Wake up!")
end)
print(wait()) --> Wake up!
print(coroutine.yield()) --> 0.041531300000088 1528.3572404038
local thread = coroutine.running()
delay(0, function()
	coroutine.resume(thread, "Wake up!")
end)
local Bindable = Instance.new("BindableEvent")
print(Bindable.Event:Wait()) --> Wake up!
Bindable:Fire() --> Here the thread scheduler tells us: cannot resume non-suspended coroutine
--It's already running; it was resumed before!

The trick is to yield as little as possible, and not being late, to allow all the scheduled threads to be on time. If a thread is yielding right after being resumed without really doing anything it’s being inneficient.

This diagram would help if it wasn’t unavailable…

5 Likes