I'm not sure what and ... how
local t = {"1", "1", "1", "1"}
t[2] = nil
t[4] = nil
print(#t) ---> 1
I'm not sure what and ... how
local t = {"1", "1", "1", "1"}
t[2] = nil
t[4] = nil
print(#t) ---> 1
See here; it says "Frequently, in Lua, we assume that an array ends just before its first nil element."
Now, "#t" is not guaranteed to work this way. The Lua Reference Manual states "The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil" (thanks to BlueTaslem for finding it); the full documentation is here. For instance, t={1,1,1} t[2]=nil print(#t) prints out 3 (though you should not rely on this behaviour, as it could just as easily print out 1).
If you need 'nil' values in a table, you have two options:
nilValue = {} and use that instead of nil# on the table; use pairs to iterate over the table (notably, this will skip over nil values)This discussion is preserved as it was. New answers, comments, and votes are closed.
4 comments
Another option is to
table.remove(t, 2)instead -- this doesn't leave a gap"The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil"
In your example #t is EITHER 1 or 3. ("If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value") [Lua reference 2.5.5]
Thanks; good points. I've updated my answer.