Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

generic for loops run more than once? [closed]

Asked by 9 years ago

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
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? adark 5487 — 9y
0
^ Goulstem 8144 — 9y

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?

2 answers

Log in to vote
2
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
9 years ago

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.

0
thank you threatboy101 2 — 9y
Ad
Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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.

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