How to make a loop that will instantly stop and restart when a variable is changed in the middle of the loop while its running

Basically the title, sorry if I couldn’t make this into the other topic I created but that topic is now gone.

I’m making a loop that needs to be stopped and restarted the moment a variable changes in the middle of it.

Couldn’t find anything bout it. Any help is appreciated!

I tried a little test:


But repeat and while don’t stop until it has carried out the code first.

1 Like

Take a look at this

for uses a number, I need an infinite loop.

Also, all these loops only stop and restart after the code has run inside it once.

Put the while loop in a function then call it. Create a variable and when that variable is true use break on all the loops and then call the function again within itself. It’ll essentially restart it.

1 Like

Here’s a simple example:

local Restart = false
local CurrentNumber = 0

function AdditionLoop ()
	while true do
		CurrentNumber += 1 
		print(CurrentNumber)
		if CurrentNumber >= 5 then
			CurrentNumber = 0
			Restart = true
			break
		end
		task.wait(1)
	end
	if Restart then
		print('Loop restarted. Number has reached 5.')
		AdditionLoop()
		return
	end
end

AdditionLoop()
1 Like

Won’t the if check be counted AFTER?

I need it to restart in the MIDDLE of the loop (and for this example I need it to stop the loop and restart at 3.)

Try optimizing the code a bit. You don’t need 3 loops to check if one single variable is a certain value.

The code I sent runs the loop and if the number hits 5 it breaks during the middle of it. The rest of the code in that loop will not run and then it will move to the if then statement. That’s where I checked if the restart variable was true. If it was, I ran the loop again.

What you could do I think for this case is have the loop inside of a function and then when the variable changes to run the function. There is no way to detect when a variable changes from my knowledge so you would probs have to sort something out like an event or something is fired.

To stop the loop you could do what @AwokenTy is saying I think but you could also have an if statement in the loop which if the variable is not a number or something then it will stop the loop via “break”.

Only numeric for loops are controlled by numbers, generic for loops are controlled by the iterated table’s size (length).

I don’t know if I should revive this (it’s sort of old), but since there isn’t a solution, here it is:
The continue keyword is like break, as in it stops a loop instantly, but it starts the loop from the top again (I think this is what you want because you were talking about “instantly stop[ing]” and restarting

2 Likes