Fast question -- error removing an element of an array

If i use

group:remove( array[u] )  
array[u] = nil  

for deleting it from the array and from the group, i get this:
start array count: 43
deleting u: 40
deleting u: 42
final array count: 39

How is that possible? if I just delete 2, why the array go from 43 to 39 (-4)?

Thanks.

PS: if i use table.remove(array,u) I get this error:
…sers\tigreton\docume~1\corona~2\sandbox\9\engine.lua:742: attempt to
index field ‘?’ (a nil value)

742 is:
print("start array count: " … #array)
or
for u=1, #array, 1 do

print("start array count: " .. #array) for u=1, #array, 1 do if array[u].option == true then --group:remove( array[u] ) --array[u] = nil --table.remove(array, u) --array[u] = nil print("deleting u: " ..u) end end print("final array count: " .. #array) [import]uid: 116842 topic_id: 29576 reply_id: 329576[/import]

Let’s look at this array:

u[1] = "hello"  
u[2] = "there"  
u[3] = "how"  
u[4] = "are"  
u[5] = "you?"  
  
print (#u) -- prints 5.  
  
u[4] = nil -- since I'm not using display objects in this example, there isn't anything to remove  
  
print(#u) -- prints 3  

u[5] still exists, but the # way of counting tables stops when it hits the first nil entry.

There are two ways to solve this…

  1. Use table.remove() to remove the entry: table.remove(u, 4); print(#u) – will output 4
  2. Use table.maxn() to print the real count: u[4] = nil; print(table.maxn(u)) – will output 4

table.maxn() ignores the nil’ed out entries. table.remove will remove the entry and collapse the nil out. Be aware that the indexes for the higher values will change. That is in this example since I table.removed item #4, then item #5 becomes item #4.
[import]uid: 19626 topic_id: 29576 reply_id: 118748[/import]

Great explanation. I changed all my code using remove, and not nil.

I don’t know how the rest of the code was working nice… hehe

I would love to give karma or something :frowning: [import]uid: 116842 topic_id: 29576 reply_id: 118839[/import]