Page 1 of 1

How to add and remove elements to the table I'm iterating in

Posted: 20 May 2009, 21:45
by zwzsg
How to add and remove elements to the table I'm iterating in:

This is more a general programming question than a Spring specific one.

I have code that goes like:

for i,e in ipairs(List) do
...
table.insert(List,...)
table.insert(List,...)
...
table.remove(List,i)
...
end

So far it seemed Lua handled it, but still, that doesn't sound very safe.
- Is Lua so good that it does magick and handle adding & removing element while iterating over a list?
- If not, what do I risk?
- What would be a sane and safe way to code this?

Re: How to add and remove elements to the table I'm iterating in

Posted: 20 May 2009, 21:58
by imbaczek
no matter the language, the answer is usually don't do that. make another table which stores keys you want to delete and do a second pass to actually delete them.

Re: How to add and remove elements to the table I'm iterating in

Posted: 20 May 2009, 22:32
by Pxtl
The traditional way is just do it after-the-fact for insertion.

For deletion, the traditional way is reverse-iteration.

The safest way is to make a new table and replace the old one with it.