Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

What is a courotine? Can you give examples of it?

Asked by
qVoided 221 Moderation Voter
4 years ago

The title says it all. The wiki is not good at explaining it. Can you explain it and give examples?

Thanks

0
The article about threading on developer.roblox is low quality and not easy even for intermediate. ErtyPL 129 — 2y

1 answer

Log in to vote
5
Answered by 4 years ago
Edited 3 years ago

Coroutines are basically a global that is used for doing things without yielding the rest of the script. It acts as a whole new script, except in one script. For example:

while wait() do
    print("Hello world!")
end

print("Bob the Builder!")

This would not work as the while wait() loop would keep on looping and never get on to the rest of the script and print "Bob the Builder!" But when we add a coroutine, it changes everything.

coroutine.wrap(function()
    while wait() do
        print("Hello world!")
    end
end)

print("Bob the Builder!")

Now it would print "Hello world!" and "Bob the Builder!"


Another example is:

coroutine.wrap(function()
    wait(5)
    workspace:ClearAllChildren()
end

print("Hello world!")

Without a coroutine, it would wait 5 seconds and then print "Hello world!", but with a coroutine, it prints straight away.


You can also give coroutines variables. For example:

local newThread = coroutine.create(function()
    print("Hola!")
end)

coroutine.resume(newThread)

Wait, why are we resuming the coroutine you may ask. That's because coroutines can be paused by using coroutine.yield(). For example:

local newThread = coroutine.create(function()
    while wait() do
        print("Hola!")
    end
end)

wait(math.pi)

coroutine.yield(newThread)

This would yield the thread (coroutine) after math.pi seconds (3.14159, etc.)


You can ALSO use arguments and parameters with coroutine.wrap(). For instance:

local newThread = corutine.wrap(function(message)
    print(message)
end)

newThread("Namaste!")

Please upvote and accept this answer if it helped.

1
Nice answer! :) killerbrenden 1537 — 4y
0
Thanks. youtubemasterWOW 2741 — 4y
1
Great answer! Accepted and upvoted! qVoided 221 — 4y
0
(so basically its like spawn) qVoided 221 — 4y
1
Yes, but spawn is considered as a bad habit since it has a built-in delay. Some can even be as long as 24 seconds. youtubemasterWOW 2741 — 4y
Ad

Answer this question