Are all indexes of a table starting from 1 until #table always a non-nil value? If not, how does #table work and how to get the actual length of a table starting from 1 until a nil value?
I’m asking this because it says my table length is 1024 yet there’re multiple nil values in that range…
To pretty much clear up everything any value in a table will be considered when u use the length operator, although if u use the length operator on a dictionary that won’t work.
Ex:
local MyDic = [“Random”]
#MyDic — wont work.
local MyTable = {[1] = 5, “apple’} — works and prints 2.
local t = {1}
t[3] = "a"
t[4] = "b"
print(#t) -- prints 4. What?
More proof:
local t = table.create(100, 1)
for i = 2, 99 do
t[i] = nil
end
print(#t) -- prints 100
The details are not documented for Luau (although they are for Lua) (edit: it actually is also undefined in stock Lua). It’s something to do with how tables pre-allocate the array part of their tables.
Basically, if you will have nil elements in your table, don’t rely on the # operator at all. It’s extremely unintuitive how it works with mixed/sparse tables and I don’t think it’s actually documented anywhere.
Edit: more discussion (and complaints) can be found in this thread
The length operator is denoted by the unary prefix operator # . The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
A program can modify the behavior of the length operator for any value but strings through the __len metamethod (see §2.4).
Unless a __len metamethod is given, the length of a table t is only defined if the table is a sequence , that is, the set of its positive numeric keys is equal to {1…n} for some non-negative integer n . In that case, n is its length. Note that a table like
{10, 20, nil, 40}
is not a sequence, because it has the key 4 but does not have the key 3 . (So, there is no n such that the set {1…n} is equal to the set of positive numeric keys of that table.) Note, however, that non-numeric keys do not interfere with whether a table is a sequence.