Can someone explain CloneTrooper1019's FastWait? | Coroutines

local RunService = game:GetService("RunService")
local threads = {}

RunService.Stepped:Connect(function ()
	local now = tick()
	local resumePool
	
	for thread, resumeTime in pairs(threads) do
		-- Resume if we're reasonably close enough.
		local diff = (resumeTime - now)
		
		if diff < 0.005 then
			if not resumePool then
				resumePool = {}
			end
			
			table.insert(resumePool, thread)
		end
	end
	
	if resumePool then
		for _,thread in pairs(resumePool) do
			threads[thread] = nil
			coroutine.resume(thread, now)
		end
	end
end)

local function fastWait(t)
	local t = tonumber(t) or 1 / 30
	local start = tick()
	
	local thread = coroutine.running()
	threads[thread] = start + t
	
	-- Wait for the thread to resume.
	local now = coroutine.yield()
	return now - start, elapsedTime()
end

return fastWait

On Git

This script never creates or wraps coroutines. Is the local function fastWait an implied coroutine function itself somehow? How does that work?

1 Like

It doesn’t need to create or wrap anything. It fetches the current running Lua thread, adds it to an upvalue “threads” where the index is the current tick() plus the time to wait.

Then a thread scheduler runs every frame, loops through the threads currently waiting to be resumed, and determines if the current tick() is now within a reasonable time for the wait to have happened.

The return never happens in fastWait until the thread is resumed by coroutine.resume

1 Like

I would not even think Roblox Script threads would be accessible given Script.Source is not. Did you consider that from reading Lua.org or just took the Roblox api as saying that? Thanks.

I got it from the code you posted and the Roblox coroutine API backs it up.

image