Why am I getting the error break statement must be inside a loop, when it is?

Hey! I’m currently making a script detecting when all the parts in a model stop moving.
The problem is, it errors when I try to break the heartbeat-loop. Error: Players.raid6n.PlayerGui.Replay:11: break statement must be inside a loop

Code:

local ExplodingModel = workspace.Model -- the model in workspace
local RunService = game:GetService("RunService")
local number = 0
local positionsdict = {} -- dictionary
game.ReplicatedStorage:WaitForChild("Event").Event:Connect(
    function()
        RunService.Heartbeat:Connect(
            function() -- loops
                if number >= 10 then -- detects if the number variable is over 10
                    print("All parts have stopped moving.")
                    break -- errors
                else -- if under 10
                    print("under 10")
                    for i, v in pairs(ExplodingModel:GetChildren()) do -- loops through the model
                        if positionsdict[v.Name] == v.Position then -- detect if the positiion didnt change
                            print("nothing changed maybe end????")
                            print(number) -- prints number
                            number = number + 1
                        else -- if the position did change
                            number = 0 -- changes to 0
                            print("yay still moving")
                        end
                        positionsdict[v.Name] = v.Position
                    end
                end
            end
        )
    end
)

How can I fix this?

Functions aren’t loops. Your break statement is not in a while x do ... end, repeat ... until x, or for ... do end. Maybe you meant return?

1 Like

Ah, okay, how can I make the function stop repeating after the number is 10 or above, though?

you can save the heartbeat connection in a variable and disconnect it when you need to.

local RunService = game:GetService("RunService")

local connection
connection = RunService.Heartbeat:Connect(function()
    connection:Disconnect()
end)

also it’s better just using a normal numerical for loop for this.
ex.

for x = 1, 10 do

end
2 Likes

Ah, forgot that was a thing, let me try that.

1 Like