How to go to the next loop in a for loop before it finishes?

can i make the for loop skip once if something is true?

1 Like

Yes you can. With the keyword “break”, which just exits the loop instantly and proceeds on. EX:

local bool = false
for i=1,10 do
  if bool = false then print(“braking”) break end
  wait(1)
end
for i = 1,10 do
   if bool then print(“hi”) wait(1) else break end
end
1 Like

keyword “continue” will skip forward once in a loop, otherwise just use break to exit out of it, or set your iterator (usually “i”) to a different number

3 Likes

Your first solution (continue) is correct but the second solution won’t work in Luau or Lua.

In Luau (and Lua), setting the for loop iterator to a different value will only affect its value during that iteration. Let’s say we have this code:

for i = 1, 4 do
	print(i)
	if i == 1 then
		i = 3
		print("i changed from 1 to 3")
	end
end

When we run it, the output will be this:

-- 1
-- i changed from 1 to 3
-- 2
-- 3
-- 4

So you are not skipping the iteration where i = 2 despite setting i equal to 3 in the end of the first iteration. In some other languages like C#, you could skip a for loop iteration this way, though. And in Luau or Lua, you could do something like this:

local i = 1
while i <= 4 do
	print(i)
	if i == 1 then
		i += 1
		print("skipping an iteration")
	end
	i += 1
end

This will give the desired output:

-- 1
-- skipping an iteration"
-- 3
-- 4

However, the continue keyword is a more practical alternative unless you want to skip multiple iterations at once.

1 Like
for i = 1, 10 do
  if i%5 == 0 then break end --stop loop when i can be divided by 5 
  -- [[code]]
end

That’s a bad practice and lua ignores the change.