table.remove stops for loop?

Posted by Trevize on Sun 10 Jul 2005 08:43 PM — 3 posts, 18,851 views.

#0
From what I've noticed it seems like when you use/call the routine (table.remove) in a table your looping it stops the loop?.. If thats the case it causes some problem for me.

Here's a test I did:

tableTest = {
{ name = "test1" },
{ name = "test2" },
}

function test()

Note("tableTest1:")
for k, v in tableTest do
Note("k: " .. tostring(k) .. ". v.name: " .. tostring(v.name))
table.remove(tableTest, k)
end

Note("tableTest2:")
for ke, ve in tableTest do
Note("ke: " .. tostring(ke) .. ". ve.name: " .. tostring(ve.name))
end

end

Frist time I run function test.
It shows:
tableTest1:
k: 1. v.name: test1
tableTest2:
ke: 1. ve.name: test2

See, at tableTest1, it aborts the loop after the first table.remove. And then the second for loop, it shows that the table now only has the second value.


The real function I actually noticed this in, is alot bigger. And it call's another function and from there I remove the value from a table that's looping in the first function, and I would like to be able to remove any amount from 0 to 1000

Is there anyway to bypass this or maybe make an alternative way of doing this? (and also, the reason I loop the table is becuase im checking it with another, so I "have" to loop the table.)
USA #1
table.remove() shifts the array elements after the removed element down in the array. So if you remove element 1, element 2 becomes element 1. My hunch is that when you remove element 1, and then move to the next position, the iterator goes to position 2, which no longer exists in the array, and therefore stops as it detects end-of-array.

Chances are that if you were iterating over not an array but an associative table with named keys (as opposed to numbers), this would work.

In general - in most programming languages - it isn't necessarily safe to remove elements from a table as you iterate over it.
#2
Ahh, thanks. Did't think about that, it makes sense..