What do coroutines do?

I am just testing to see what do coroutines do, I looked at the Developer Forums about this and even looked at the Roblox Documentation and they say that it said that “A coroutine is used to perform multiple tasks at the same time” so i tested it.

I wrote this code:

local function loadSomethingVeryLong ()
	debug.profilebegin("Coroutine: LoadingSomethingThatTakesAWhile")
	local a, b = 0, 1
	for i=1, 1000000 do a, b = b, a end
	debug.profileend()
end

local RunService = game:GetService("RunService")

RunService.PreRender:Connect(function()
	coroutine.resume(coroutine.create(loadSomethingVeryLong))
	
	debug.profilebegin("LoadSomething")
	local a, b = 0, 1
	for i=1, 100000 do a, b = b, a end
	debug.profileend()

	debug.profilebegin("LoadAnotherThing")
	local a, b = 0, 1
	for i=1, 100000 do a, b = b, a end
	debug.profileend()

	debug.profilebegin("LoadAnotherThingAgain")
	local a, b = 0, 1
	for i=1, 100000 do a, b = b, a end
	debug.profileend()
end)

And heres the result of the code:

I thought that coroutines were supposed to run somewhere else and let the other code below it run asynchronously with it, kinda like parallel scripting. (Either that or im just really dumb and missed something)

Can someone pls explain what coroutines are actually useful for?

2 Likes

The basic idea of coroutines is to perform a function in which you have to yield something separately from your other code. It is very useful for running multiple loops in a single script, for example:

local seconds = 0
local minutes = 0

while task.wait(1) do
	seconds += 1
	print(seconds.." seconds have passed.")
end

--this while loop would never run as the loop above it has paused all the code below.
while task.wait(60) do
	minutes += 1
	print(minutes.." minutes have passed.")
end

Using coroutines, we can solve this:

local secondsLoop = coroutine.wrap(function()
	while task.wait(1) do
		seconds += 1
		print(seconds.." seconds have passed.")
	end
end)

local minutesLoop = coroutine.wrap(function()
	while task.wait(60) do
		minutes += 1
		print(minutes.." minutes have passed.")
	end
end)

secondsLoop()
minutesLoop()
--both functions will run simultaneously since they are both wrapped in a coroutine.

Another example using for loops:

local count = 0

local increaseCount = coroutine.wrap(function()
	for i=1,10 do
		count += 1
		task.wait(3)
	end
end)

increaseCount()
task.wait(3)
increaseCount()
--this allows for the function to be run twice without waiting for the first increaseCount function to finish.
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.