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
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)).
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.
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