I have found that a table with nil and more values afterwards will lose all values after the nil value. And when getting the length of the table, it will only count the values before the nil value. Example:
mytable = {1, 2, nil, 3, 4} print(mytable[2]) -- outputs 2 print(mytable[3]) -- outputs nil print(mytable[4]) -- outputs nil print(mytable[5]) -- outputs nil print(#mytable) -- outputs 2
Is there any way to get around this and still have the nil value in the table?
That's normal behavior
#mytable
returns the length of the array part of mytable
, which is the part of it that starts at mytable[1]
and counts up, stopping at the first nil
value.
You can iterate over all the keys of a table (not just the array part) with the pairs
iterator, which means you can count the indices like so:
function countKeys(t) local count = 0 for _, _ in pairs(t) do count = count + 1 end return count end
If you only want to count integer keys, you can do that like so:
function countIntegerKeys(t) local count = 0 for key, _ in pairs(t) do if type(key) == "number" and key % 1 == 0 then count = count + 1 end end return count end
For example:
local t = { [1] = "a", [2] = "b", [4] = "test", ["hello"] = "world" } print(countKeys(t), countIntegerKeys(t))
would print 4 3