What will this break?

I can write a couple of loops with a break inside of one of them that look like this:

while someCondition do
    for i = 1, 100 do
        if someCondition_2 then
            break
        end
    end
end

And I also have a loop that looks like this:

while someCondition do
    if someCondition_2 then
        break
    end
end

Now, if someCondition_2 in the second script is true, the while loop will break, and the script will end. But what if someCondition_2 is equal to true in the first script? It will obviously break, but will it break out of the for loop, and the while loop? Or will it just break out of the for loop?

1 Like

It will break out of both loops

Is there any way to control what loops it breaks out of?

1 Like

No, because you’re checking against the same variable. Maybe try using a different one or resetting the variable to false once it’s broken out of one of the loops

Thats not… true? It would only break out of the for loop

can you explain why you think that?

I actually have two different conditions. In the if statement, I am checking against someCondition_2, but in the while loop, I am checking against someCondition.

@DataSigh I just tested this in studio and it doesn’t break outside of both loops:

local r = math.random(5, 200)
while game:GetService("ReplicatedStorage").TestValue.Value do 
    task.wait() 
    for i = 1, r do 
        if i == 46 then 
           print('end') 
           break 
        end 
     end 

     print('pass') -- the two prints continue to run even after break is used
end

Just tested it.

local d = 1

while true do
	task.wait()
	print("while loop")
	for i = 1, 5 do
		task.wait()
		d += 1
		print(d)
		print("for loop")
		if d >= 4 then
			break
		end
	end
	print("for loop broken")
end

Seems like the while loop is ignoring the for loop yielding. and none of them broke.
image

you can just test this

while task.wait(1) do
	
	for i=1,10 do
		print(i)
		if i==5 then break end
	end
	
	print('looping')
end

and it will still run the while loop, and therefore, the for loop again
image

1 Like

ahhh didn’t notice that when reading the post, gotcha

It breaks out of the first loop.