Hello Developers! ![]()
What are some use-cases of when to use Coroutines? Thanks ![]()
Hello Developers! ![]()
What are some use-cases of when to use Coroutines? Thanks ![]()
If you want information about Coroutines. I recommend looking here: coroutine | Documentation - Roblox Creator Hub
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.
O. So I use coroutines when I would want to run things simultaneously at the same time?
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??
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.
You can also look for more coroutines in the documentation
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)
Yes
If you run the function: eg()
“Test” won’t be printed, but using coroutine.resume will resume the coroutine, now “Test” will be printed