Instantly going through a for loop?

Say you had a for loop, something like this:

for  i,v in ipairs(game.Players:GetPlayers()) do
   --loop content
   wait(5)
   --remaining loop content
end

Are there any way of looping through all the players instantly, without having to wait 5 seconds to restart between each loop? I still want the script’s content to wait 5 sec tho, but it would be great if it could start on the second loop before it’s finished with the wait command. I’ve tried to put the content in a function outside the loop, and call it from inside the loop, but that seems to do the exact same thing.

There are a few ways you could do this. You could use a single thread with separate loops:

for  i,v in ipairs(game.Players:GetPlayers()) do
   --loop content
end
wait(5)
for  i,v in ipairs(game.Players:GetPlayers()) do
   --remaining loop content
end

or you could use separate threads created at (almost) the same time:

for  i,v in ipairs(game.Players:GetPlayers()) do
   coroutine.resume(coroutine.create(function()
      --loop content
      wait(5)
      --remaining loop content
   end))
end
3 Likes

Personally I think the second method looks cleaner, I don’t think either of them have any performance benefits and even if they did I’m sure it’d be a micro-optimization.

Also, spawn(function) is a much cleaner alternative to coroutine.resume(coroutine.create(function)).

3 Likes

Yeah, I’ve just always preferred to use coroutines. spawn() is nearly identical.

I believe the first method is more efficient, although it’s just a micro-optimization (as you said). The second method is much cleaner and easier to read in long scripts.

Dude, that actually worked!

Been trying to figure this out all day, thanks.

If the second operation depends on the first operation, the first method risks failing because it recollects the list of players after waiting. If a player joins or leaves during the wait, the list will change. If you use this method, I’d recommend amending it to:

players = game.Palyers:GetPlayers()
for  i,v in ipairs(players) do
   --loop content
end
wait(5)
for  i,v in ipairs(players) do
   --remaining loop content
end
4 Likes

Oh yeah, forgot about that situation. Definitely use this over the other option unless you can be bothered to make it handle this case correctly.

I’ll just go with coroutine.resume :stuck_out_tongue_closed_eyes:

1 Like

You can also do something like this for brevity:

coroutine.wrap(function()
       print("Hi")
end)()

Or if you prefer spawn() you can use that too.

What’s the difference?

Another thing you could do is

for i, v in ipairs(game.Players:GetPlayers()) do
     --Content
     delay(5, function()
          --remaining content
     end)
end
2 Likes