Quick little question on loops and break behavior

Is there a quick way to stop a “for _,v in pairs(list) do” loop without also ending any other loops/functions that the loop is in?

lets say you are trying to change one red rock to blue in a list of rocks. In this list there are several red rocks.

for _,rock in pairs(rocks) do
if v.BrickColor == "Bright red" then
rock.Color = Color3.new(0,0,1)
-- break? What just ends the loop without also ending the function that the loop is in?
end
end
-- rest of script

I figure I’m either misunderstanding one of these commands or there’s a command I don’t know about to do this right? Does break just end the loop or function you use it in or does it translate to it’s parent loops/functions?

1 Like

break only stops the loop that the break statement is in.

repeat -- loop A
    repeat -- loop B
        break -- breaks loop B, not loop A
    until true
until true
1 Like

break is your friend in this case.
Break is a control statement in Lua that transfers the control over to the first statement outside the loop.
Example:

for i = 1, 5 do
    if i == 2 then
        break
    end
    print(i)
end
print("post-loop")

Output:

1
post-loop
1 Like

As @Imagine_Developing said break is what you would do. Alternatively though, you can also just do

return

and that will also signify the loop is complete.

1 Like

Perfect thank you! I figured break ended all loops for whatever reason

1 Like

It will also return from the enclosing scope (the function or script).

function foo()
    return -- will return from foo
    
    local function bar()
        return -- will return from bar
    end
end

return -- will return from script
1 Like

In addition to the information that has already been provided you may want to learn about the ‘continue’ statement, it’s exclusive to Luau.

1 Like