How to constantly check a variable while in a loop and restart the loop if the check succeeds

I’m trying to make a system where if suddenly a player leaves during this while wait() do statement, the loop will reset.

I’m using a PlayerRemoving function for this since I don’t know how I can infinitely check every second inside the while wait() do loop (but if you do that could help solve this)

image

Any help is appreciated!

2 Likes
local currentCount = #game.Players:GetChildren()

while wait(1) do
     if #game.Players:GetChildren() >= currentCount then
        -- do whatever it is you wanna do
     end
end

I dont understand reseting this loop because while wait(1) do never ends, so doesnt need reset

This only checks once through the entire loop. I need something that infinitely checks through the loop and when the check actually happens, It will restart the loop.

You can use break inside a loop to stop it.

Completely not the topic, dude. I know how to restart a loop BUT I want to do it with an infinitely checking line of code inside the while wait() do…

Dude, clearify your problems better. Once again, while wait(1) do is infinite, so whatever you write inside it it checks infinitely. You cant restart it, because it doesnt have an ending

Then how would I stop the code and take it back from the top.

You can put your loop inside a function, and when you wanna restart it, break the loop and call the function again (You can call a function inside the same function thus creating sort of an artificial loop)

Can I get an example of how I would do that?

Sure

local loopBool = true
local function repLoop()
 loopBool = true
 while loopBool == true do
    wait(1)
     if #game.Players:GetChildren() < currentCount then
        loopBool = false
       repLoop()
     end
 end
end

repLoop()

In this case “Break” wouldnt work because whatever you write after a break, doesnt get executed, so i used a bool

oh and make sure to add wait(1) inside your loop or it will be extremely heavy on performance

Just tested the built-in function continue in game and it’s resetting my original loop back from the top already.

image
(Printed 2-5 then restarted the loop at continue)

So now, were back to how I can infinitely check a variable inside the loop WITHOUT roblox events I guess since they don’t allow loop based functions inside the code. So how can I constantly check?

Have you tried this? It check the same thing you wanna check just without an event

But does it constantly check while the loop is in the middle of running?

use

repeat wait() until -- thing happens 
while task.wait(1) do
	repeat task.wait(1) until #game.Players:GetPlayers() >= 2
	
	game.Players.PlayerRemoving:Wait()
	if #game.Players:GetPlayers() < 2 then
		continue
	end

end

This will stun the code if I put it inside the loop.

This will also stun the code when there will be other code below the code checking if the players suddenly change.