imagine youre running through a table, checking if the items in the table meet a criteria. you want your loop to end if the criteria is met, but you need to run more code when the criteria is met, and only when the criteria is met, so you cant just put the code after the loop.
for i, v in pairs(table) do
if thing then
break
--run code
end
end
would something like this work? does breaking end the loop completely, or would it still run the code afterwards?
(i know i could put the break after the “run code” part but in my example i couldnt do this)
if you want more context, heres the full example
i have something like this
for i, v in pairs(table) do
if partMeetsCriteria then
for i, v in pairs(table) do
if partMeetsDifferentCriteria then
end
end
end
basically, if the part meets the first criteria, i want it to move on to the next one. if it meets the second criteria, i want it to move on with the script. however, it would then move on to the next part in the first “in pairs” loop, and i dont want that. would i just include a break at the end of the second in pairs loop?
Any sort of loops that are breakable & calling the break command if those specific requirements are met, will forcefully stop the loop from going & continuing through every object inside the table
local Table = {"Banana", "Orange", "Grape", "Apple", "Table", "Pomegranate"}
for _, Fruit in ipairs(Table) do
if Fruit == "Table" then
print(Fruit, "is not a fruit at all! Break this loop!")
break
else
print(Fruit, "is a fruit!")
end
end
-- Pomegranate will never print, because we broke the loop after we reached the "Table" string
function doSomething()
doSomething()
print("hello")
end
will hello ever be printed? basically what im trying to ask is, if i call a function from inside itself, will the code following the function call ever be executed?
No. The program just executes every single line seperatly. It does basically not know yet that there’s something to print behind the doSomething() function. That’s why it just does exactly what it gets told. It can’t know when the function ends (this is only possible when the program runs into an end), so it will just repeat callling doSomething() function.
Ideally you should avoid using break or continue as much as possible when writing code. It is usually a logic error to use these keywords and the code can be refactored to run without them.
In your case, your example
for i, v in pairs(table) do
if partMeetsCriteria then
for i, v in pairs(table) do
if partMeetsDifferentCriteria then
end
end
end
You could re-write this code by creating an empty table, and inserting any parts which meet both criteria. After you are finished looping, you will have an array solely of criteria-fitting objects which you can manipulate afterwards.
PsuedoCode Provided
local ObjectsInCriteria = {}
for i, v in pairs(table) do
if partMeetsCriteria and partMeetsDifferentCriteria then
table.insert(ObjectsInCriteria, ObjectFittingCriteria)
end
end