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

How can i run 2 loops at the same time?

Asked by 8 years ago

I want to know how to run 2 loops at the same time. When i try this V

for i = 0,10 do
    print("Test")
end

for i = 0,5 do
    print("Test2")
end

Is it possible to run those at the same time?

1
You can use Coroutines, Spawn, or put the code in the same loop with if i%2 == 1 then for the 2nd print("Test2") RubenKan 3615 — 8y
0
Very helpful,thanks alot. kristibezatlliu1111 33 — 8y
0
There's also delay, similar to spawn :P OldPalHappy 1477 — 8y

1 answer

Log in to vote
0
Answered by
cabbler 1942 Moderation Voter
8 years ago
Edited 8 years ago

Like you have already read, you can easily do this by using spawn(function) or spawn(function() end). If that's not it, then wiki coroutines for some useful functions.

It is actually not possible to run two loops at exactly the same time - as in executing their lines at the same time or alternating. What happens when you use a coroutine is you put the function into the task scheduler, then your other code continues. This is the same for scripts too. The task scheduler simply runs specific code until a yield, then finds new code to run until it yields, then a new one which can even be the previous. This is efficient because the code runs so fast that you can't notice the separation.

If you do this:

spawn(function()
    for i=1,5 do
        print(i)
    end
end)

for i=6,10 do
    print(i)
end

Look at the output and you actually see it print 6-10, then 1-5. Because it continued your code until it yielded then went to the other code to be efficient.

The point being that you should try to use coroutines as little as possible, because what it does isn't really that crazy. If neither of your functions yield then there is no reason at all. And if you are looking for alternating lines then coroutines won't do it for you. Otherwise good luck!

Ad

Answer this question