issue removing table elements?

My array has 2 elements in it, I want to basically delete everything in the array so I use this block of code, but at the end of the block it still says the #spaceMen is equal to 1…

for i, v in ipairs(spaceMen) do
v=nil;
table.remove(spaceMen, i);
end

[import]uid: 6317 topic_id: 1098 reply_id: 301098[/import]

Generally, if you want to delete everything in a table, iterate BACKWARDS over it. Otherwise, the length of the table changes during the iteration and it doesn’t work properly.

Also, if it’s just an ordinary data table, you could do:

spaceMen = {} [import]uid: 3007 topic_id: 1098 reply_id: 2794[/import]

Or like Evan mentioned:

[lua]
for i = #spaceMen,1,-1 do
table.remove(spaceMen, i);
end[/lua] [import]uid: 5712 topic_id: 1098 reply_id: 2797[/import]

What about

for i = #spaceMen,1,-1 do  
 spaceMen[i]=nil  
end  

which runs about 25% faster in this testcode

local i,n,t,s  
local tRemove=table.remove  
collectgarbage("collect")  
collectgarbage("stop")  
print(collectgarbage("count"))  
s=system.getTimer()  
for n=1, 1000 do  
 t={}  
 for i=1,10000 do  
 t[i]={i}  
 end  
  
 for i = #t,1,-1 do  
-- table.remove(t, i);  
-- tRemove(t, i);  
 t[i]=nil  
 end  
end  
print("time: "..(system.getTimer()-s))  
print(collectgarbage("count"))  
collectgarbage("restart")  
collectgarbage("collect")  
print(collectgarbage("count"))  

I tested some garbage collector related stuff with that code earlier too. Kinda useless though besides of getting better results for direct comparison of implementations.

But for the OP example the t={} … or t=nil would be of course the best solution :slight_smile: [import]uid: 6928 topic_id: 1098 reply_id: 3238[/import]