Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

generic for loops run more than once?

do generic for loops run more than once? for example if you are looping through a model to put all its children into a table and removing them will it keep looping and add those children that you already removed?

This is a simple yes or no question.

2 comments

2

Just so you know, questions that only require a yes or a no answer are not well suited to this site. You can do simple testing on your own, can't you?

0

^

2 answers

✓ Accepted answer

No

Generic for loops do not run more than once. Unless they're in the scope of another loop.

Although, there is a differentiation between the pairs function and ipairs function, it does not effect how many times it iterates.

pairs : Will error if comes across a nil index in the table you're iterating through.

ipairs: Will not error if comes across a nil index in the table you'reiterating through.

1 comment

0

thank you

The iterator expression (expression between in and do) is only executed once^1. However, you pass a table, which is passed by reference, so changes to the table during the loop body might cause the iteration's behavior to change.


I found an old reference to the question

What happens when you modify a table while iterating over it?

An answer, quoting some Lua reference manual, was

The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table.

Assigning values to already existing keys is fine.

Source

I think since table.remove adjusts other keys, you might have a problem.


If you want to be safe, just iterate backwards:

for i = #list, 1, -1 do
	if math.random(2) == 1 then
		table.remove(list, i)
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.