Getting data on array returning incorrect results?

I have a system in place to get an array of data and process that data inside the array. For some reason, getting info on the array (such as the length of the array) returns seemingly random values.

print("Array length : "..#formattedData)
print("Type : "..type(formattedData))
print("Data :")
print(formattedData)

I ran this same code twice on different arrays and they both produced different outputs, yet similar results.
As you can see in the first image, it says the length is 1 yet the data in the array shows there are more entries. The weirdest one is in the second image as it says the length is 0? Am I missing something here? I’ve been stumped by this for a while now and I’m certain that something has gone over my head.

Screenshot_1239
Screenshot_1240

The length of the array is counted from 1 to n incrementing by 1, with n being the last integer before the pattern is broken.
In your first image, you skip 2, meaning the +1 pattern stops at 1. In your second image, there isn’t even a value (1) to start counting from.

2 Likes

Do you have any values that are not indexed by numerically contiguous indices? The length operator only makes the count if keys i[1] … i[n] are numerically contiguous. If you don’t have a gapless numerically contiguous table, length will only return ordered keys.

If you need to count a table that may have gaps or other indices, go through it with pairs.

for _, _ in pairs(tbl) do
    count += 1
end
4 Likes

Cannot believe that I’ve been working with Lua for almost 2 years now and I have never known this. Both replies very helpful, thanks :grin:

2 Likes