Equivalent of a "continue" statement in for loops

Lua doesn’t seem to have continue as in other programming languages like C++/Java, what is some simple statement to make a for loop terminate to the next iteration (without having to make if structures)?

1 Like

Split your iterations into functions that you can return from at any time so that the function stops but the loop keeps going.

3 Likes

The best way I know of, although kinda ugly is this:

for i = 1, 30, 2 do
	repeat
		-- code
		if bleh then
			break -- basically a "continue"
		end
		-- code
	until true
end

for i, v in next, blah do
	repeat
		-- code
		if bleh then
			break
		end
		-- code
	until true
end

while condition do
	repeat
		-- code
		if bleh then
			break
		end
		-- code
	until true
end

It’s faster performance wise than function calls, too.

4 Likes

Did you forget

while X do
	while Y do
		wait()
	end
	wait()
end

A simple way to use continue is to wrap whatever is in the loop inside a function and use return if the condition that you want to use continue at is met.
Example :

local function Delete(v)
    if not v:IsA("BasePart") or v.Name == "Baseplate" then return end
    v:Destroy()
end
local function ColorPart(v)
    if not v or not v.Parent then return end
    v.Color = Color3.new(0,0,0)
end
for i,v in next, game.Workspace:GetChildren() do
    Delete(v)
    ColorPart(v)
end

I only would use this if I need to wrap certain parts of the loop inside an if statement and there are too many ends in the code that would make me take awhile to find the right spot for it , or if I want to use continue without having to wrap everything inside an if statement and there is no continue so if i wrap everything inside a function using return in that function is like using continue.

Also putting your code inside functions like that helps with being able to easily read your code without having to go through all the details.

I just thought I should share this because I had the same question before realizing the solution, might not be a solution to many people as wrapping things inside an if statement is easy but I hope I’ve helped :slight_smile: .

2 Likes

Or use the continue statement—which now exists :rofl:

15 Likes

Oh I didn’t know it existed , because I don’t wanna use it for my game while it’s still in beta.
Thanks for pointing it out , and is it safe to use?

i’ve had no problems with it thus far, just make sure you don’t have any variables named continue

1 Like

I meant Luau VM beta not sure if it’s safe to use in my game. but thanks I’ll be using it from now on then.