Can someone explain co-routines to me?

I’ve watched a couple videos to no avail, can someone enlighten me on what it does and how to script one?

I’m not the best at coroutines, but they allow you to run code without interrupting/pausing the current code. You can yield them (stop them) and you can resume them.

local co = coroutine.create(function()
    task.wait(5)
    print("test")
end)

coroutine.resume(co)--prints test after 5 seconds
print("a") --prints a immediately (before test)

It sort of works like task.spawn() besides the fact that you can stop it.
You can also yield the coroutine like this:

local co = coroutine.create(function()
    print("test")
    coroutine.yield()
    print("test#2")
end)

coroutine.resume(co)--prints test
coroutine.resume(co)--prints test#2
1 Like

in script you cant run two infinte loop in one script cuz one on of them in top will work inifinty
with corotuine you can run two in one script

local cor = coroutine.create(function()
	
	while wait(1) do
		print("Oh Multi task here")
	end
end)

coroutine.resume(cor)

while wait(1) do
	print("first here")
end

https://developer.roblox.com/en-us/api-reference/lua-docs/coroutine

1 Like

so while the coroutine happens its also moving on to the other pieces of code down the line without getting hooked on the function and waiting till its done?

yea its like you made new script and paste code into it its like
script in script

thanks for the help guys, i get it now.

Correct. When you run a coroutine, the code inside the coroutine runs while the script continues to run everything outside of the coroutine. Coroutines are very useful in cases where you have to perform multiple tasks at the same time, inside the same script. For example, if you need a timer to run while running something else.

1 Like