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

What is Coroutine? [closed]

Asked by 10 years ago

For a long time life of Lua, one thing that is really makes me to ask. What is Coroutine and other Coroutines? This kind of Lua that I want to be use at my scripts? Please help me!

Locked by TheeDeathCaster, BlueTaslem, TofuBytes, and Aethex

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

1 answer

Log in to vote
8
Answered by 10 years ago

Well basically, a coroutine is a ROBLOX function that breaks the Lua sequence. What does this mean? Well, let's say you had two while true do loops, like so:

while true do
    --Code here
end

while true do
    --Code here
end

Now, we both know that this won't work, because scripts are read in a sequence (top to bottom). The first loop is going to keep executing code until it stops (which it won't), and then it will move onto the code under it, which is the second loop. But with coroutines, we can allow two or more loops to run at once.

coroutine.resume(coroutine.create(function()
    while true do
        --Code here
    end
end))

while true do
    --Code here
end

Now I know this might look confusing at first, but it's really not. What the coroutine is doing, is that it's sort of "breaking" the scope away from the sequence. So the script will read the code from top to bottom, see that there is coroutine, and run the code as if the first while true do wasn't even there. For example:

coroutine.resume(coroutine.create(function()
    while true do
        print("This was printed under a coroutine!")
        wait(1)
    end
end))

while true do
    print("This was not")
    wait(2)
end

Basically, what this is going to do is that it's going to print "This was printed under a coroutine!" every second, and at the same time print "This was not" every two seconds. This can be very useful if you want multiple scopes working at once. For more information on coroutines, click these two links: Beginners Guide to Coroutines or Coroutine Tutorial. Hope this helped!

2
The word you are looking for is 'thread'. Coroutines run in their own threads, as do individual Scripts and LocalScripts. adark 5487 — 10y
Ad