Getting the length of an array that does not start at 1

I want to remove an array that does not start at 1 when it is empty. The problem is that # always returns 0, even when the array contains items.
I found this: How to get the count of items in a table
The post says that for a dictionary, you need to iterate over the contents to find the length. That would most likely work as I can use pairs() to iterate (not ipairs()) over the array. But this is not a dictionary as the indices are numbers, not strings.
Is there any way to find the length of this array that does not require iterating over it manually?

local array={[5]=1,[6]=1,[7]=1,[8]=1}
print(array)
print(#array)

image

local length = 0
local array = {[5] = 1, [6] = 1, [7] = 1, [8] = 1}
for _ in pairs(array) do length += 1 end

print(array) 
print(length) 

ā–¼ {
[5] = 1,
[6] = 1,
[7] = 1,
[8] = 1
}
4

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.