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?
How to add and remove elements to the table I'm iterating in
Moderator: Moderators
Re: How to add and remove elements to the table I'm iterating in
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
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.
For deletion, the traditional way is reverse-iteration.
The safest way is to make a new table and replace the old one with it.