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.
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.
The iterator expression (expression between in
and do
) is only executed once1. 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.
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
Locked by SanityMan, Operation_Meme, TheeDeathCaster, and Redbullusa
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?