How to stop looping after something is found in an array?

How can I achieve the following?

This is what I currently have:

for i, v in placedPartArray do -- just an array of parts
	if v.Position == preview.Position then -- if part position matches the position I want
		print("this value is the one I'm looking for")
	end
	if v.Position ~= preview.Position then -- if part position doesn't match the position I want
		print("this value isn't it")
	end
end
-- do something ONLY if the position is found

-- I have other things in this script, so deleting it isn't an option

How do I stop the script, or continue it? Thanks!

You can use the break keyword. This will prevent a loop from continuing and will exit the loop.
You can also have a variable that checks if the position was found.

local isPositionFound = false
for i, v in placedPartArray do -- just an array of parts
	if v.Position == preview.Position then -- if part position matches the position I want
		isPositionFound = true
		print("this value is the one I'm looking for")
		break -- stops the loop and continues whatever's under it
	end
	if v.Position ~= preview.Position then -- if part position doesn't match the position I want
		print("this value isn't it")
	end
end
-- do something ONLY if the position is found
if isPositionFound then
	-- do stuff here
end
-- I have other things in this script, so deleting it isn't an option

You can read more in Control Structures.


Wow, you’re right! Thank you! :smiley:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.