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

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

Discuss Lua based Spring scripts (LuaUI widgets, mission scripts, gaia scripts, mod-rules scripts, scripted keybindings, etc...)

Moderator: Moderators

Post Reply
User avatar
zwzsg
Kernel Panic Co-Developer
Posts: 7052
Joined: 16 Nov 2004, 13:08

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

Post 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?
imbaczek
Posts: 3629
Joined: 22 Aug 2006, 16:19

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

Post 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.
User avatar
Pxtl
Posts: 6112
Joined: 23 Oct 2004, 01:43

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

Post 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.
Post Reply

Return to “Lua Scripts”