Use-Cases of Coroutines?

Hello Developers! :wave:

What are some use-cases of when to use Coroutines? Thanks :wave:

1 Like

If you want information about Coroutines. I recommend looking here: coroutine | Documentation - Roblox Creator Hub

1 Like

I would say when you want to have different pieces of code running asynchronously so they don’t interrupt your actual script. For example, a task that loops often might want to be put into a coroutine.

2 Likes

O. So I use coroutines when I would want to run things simultaneously at the same time?

1 Like

Yes, you would use coroutines.

So basically to sum it up, a coroutine is a function and you use it to run things simultaneously like when you want loops to run at the same time??

1 Like
game.Players.PlayerAdded:Connect(function(plr)
local msg = Instacne.new("Message", plr.PlayerGui)
msg.Text = "Welcome "..plr.Name
while true do
  print("String") 
  wait(2)
end
print("Test")
end)

…
wait a minute, “Test” wasn’t printed?
Well, that’s because the code didn’t run after the loop.
But we can fix that using a coroutine

game.Players.PlayerAdded:Connect(function(plr)
local msg = Instacne.new("Message", plr.PlayerGui)
msg.Text = "Welcome "..plr.Name
coroutine.wrap(
while true do
  print("String") 
  wait(2)
end
)() -- everything here will run, now the script will still run over the next lines
print("Test")
end)

But this time… “Test” was printed.

1 Like

You can also look for more coroutines in the documentation

1 Like

Does this work too:

game.Players.PlayerAdded:Connect(function(plr)
local msg = Instance.new("Message", plr.PlayerGui)
msg.Text = "Welcome "..plr.Name

local eg = coroutine.create(function()
    while true do
        print("String")
        wait(2)
    end
    coroutine.yield()
    print("Test")
end)



coroutine.resume(eg)
coroutine.resume(eg)
1 Like

Yes

2 Likes

If you run the function: eg()
“Test” won’t be printed, but using coroutine.resume will resume the coroutine, now “Test” will be printed

1 Like