How do I break out of a in pairs loop within a conditional statement in the loop

I’m trying to make this in pairs loop break inside the if statement that’s in the loop.

for i,v in pairs (mytable)  do
				if v == player then
					mytable[player] = true
                    --- I want it to stop the for loop here
					else 
					mytable[player] = false
				end
			end
2 Likes

at — I want it to stop the for loop here u need to put break

1 Like

How does the break know what loop to break though?

for example

while true do wait() ---loop 1
while true do wait() ---loop 2
if true = true then
break

             end
      end
end

what would the break stop in that scenario, the first or 2nd loop?

1 Like

The most common ways to break out of a pair loop, or most loops in that matter, are Return and Break. Return will break but instead of just breaking it will give a value well, “in return”. Break will stop the loop completely, without returning any sort of value. @Scrizonn in that scenario the break will stop the loop it is in( the inner loop), not the outermost

1 Like

you can break only things like:


for i, v in next, Mytable do
break
end

or


for i,v in pairs(aTable) do -- or ipairs
break
end

i’m pretty sure you can break out of while loops too

Return is for functions, not loops. These are different keywords with different purposes and shouldn’t be used interchangeably.

Edit in response to second post: You can break any type of loop though, you are correct.

@Scrizonn It will break the innermost loop, so the second one.

2 Likes

You can break out of while loops too.

Technically wouldn’t it still give back a value( like if you have a while loop nestled in a function) , but i do see your point that they should be more often used in function

Example of what i mean
function Test()
while true do
	wait(.1)
	return 5
     end
end 

print(Test()) -- this will still print 5

in what u said, that break will stop the loop 2

That only works because it’s in a function and return will immediately stop running any further code in the function.

2 Likes

Good point, thank you for correcting me!

Don’t worry i know how to use return :sweat_smile:, i just didn’t explain it correctly. also i am a bit tired so that probably doesn’t help either

1 Like

Yeah, I could tell from the code sample you knew how to use it. I just wanted to make sure it was clear to anyone else reading this who might not be aware.

2 Likes