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

1 script and 2 while loops running at once?

Asked by
4jne 18
7 years ago
Edited 7 years ago
while wait(1)do
print'1'
end
while wait(2)do
print'2'
end

It never prints 2. Is it possible to make the both while loops start running at once without putting them into two different scripts?

0
From what I know, you can't run two separate loops at the same time unless one was inside a function that was fired by an event while the same script was looping something else. Troidit 253 — 7y

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

Spawn

First of all: don't use coroutine if you're only using it to make "threads" that make code "happen at the same time".

A good test: if you're not meaningfully using coroutine.yield, don't use coroutine at all.

Instead, use spawn and delay to create "background threads"

spawn(function()
    -- "in the background" loop
    while true do
        print("background loop")
        wait()
    end
end)

while true do
    print("foreground loop")
    wait()
end

Avoid threads

Second of all: it is usually a mistake to use spawn / have multiple threads. Your code can really quickly become confusing and complicated.

By interleaving work, you can do multiple things at the same time, in a very controlled way.

e.g., why wouldn't you just use this instead?

while true do
    print("background loop")
    print("foreground loop")
    wait()
end

See these threads for more detailed examples:

Ad

Answer this question