Very weird table behavior

Now this may just be my lua n00bness, but I think this behavior is a bug and will make me have to revisit all my games.

I’ve always made the assumption that #mytable would return the number of entries in a table. It does not. It returns a count of items until it hits the first “nil” entry.

See this block of code:

t = {}  
print("#t = ", #t)  
  
t[1] = "fred"  
for i =1,3 do print(i,t[i]) end  
  
print("#t = ", #t)  
  
t[2] = "barney"  
  
print("#t = ", #t)  
for i =1,3 do print(i,t[i]) end  
  
t[3] = "wilma"  
  
print("#t = ", #t)  
  
for i =1,3 do print(i,t[i]) end  
  
t[2] = nil  
  
print("#t = ", #t)  
for i =1,3 do print(i,t[i]) end  

with these results:

#t = 0  
1 fred  
2 nil  
3 nil  
#t = 1  
#t = 2  
1 fred  
2 barney  
3 nil  
#t = 3  
1 fred  
2 barney  
3 wilma  
#t = 1  
1 fred  
2 nil  
3 wilma  

So basically I add a new entry to my table “t” one at a time. You see that #t increments as it should. By the time “wilma” is added to the list everything is working as necessary.

Then I nil out barney (the 2nd cell) and now #t returns 1, not 3.

This means if you are using a table to track your objects on screen and your player kills one in the middle and you are dependent on #table to return you the length of the table (or anytime else you’re using #table) you can expect problems.

Someone please do a quick test with the above code and sanity check me please…

Do I need to file this as a bug report?

Rob [import]uid: 19626 topic_id: 20784 reply_id: 320784[/import]

Lua uses nil to define the end of the table. Not a bug. Depending on how you use the table, there are alternatives.

Here is some info on using nil in tables:
http://lua-users.org/wiki/StoringNilsInTables
Jeff

[import]uid: 14119 topic_id: 20784 reply_id: 81736[/import]