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?
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
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: