Why Isn't This Working? Attempting To Read Length Of Table

Why isn’t this working? This has kind of got me head-scratching…

local TestDict= {
    ["Test"] = {
        1,2,3
    },
    ["Test2"] = {
        1,2,3
    },
}

print(#TestDict) -- get length of table (number of indices)
--> Prints: 0

It’s just a dictionary with a bunch of numbers in it. None of my other tables / dictionaries cause an issue when attempting to read them. Even when I do this exact thing. It’s just a table with tables in it…

I expect it to print 2, not 0.

Maybe try this: I don’t know why that isn’t working either

local MapDataDict = {
    ["Test"] = {
        1,2,3
}
    ["Test2"] = {
        4,5,6
}
}

print(#MapDataDict)
1 Like

Attempted this, still prints 0 for some odd reason.

Interesting, have you updated studio recently? Maybe try restarting studio?

Dictionaries do not have a length. You would need to go over it with a loop to get the length.

local TestDict= {
    ["Test"] = {
        1,2,3
    },
    ["Test2"] = {
        1,2,3
    },
}

local count = 0

for i,v in pairs(TestDict) do
    count += 1
end

print(count)
6 Likes

Been coding for like 6 years and I never knew this, thanks.

But why don’t they have length?

Honestly, I’m not sure of the reason myself. I just know that it doesn’t count the tables inside of the table, but if you were to also have a normal value like this:

local TestDict= {
    ["Test"] = {
        1,2,3
    },
    ["Test2"] = {
        1,2,3
    },
    1,
    2,
    3
}

print(#TestDict)

it should print out 3. Also, as far as I know, it’s like this in every language, but a bit different. For JavaScript, {} is an Object and [] is an array. Arrays have a .length property, but an Object doesn’t and you need to get the number of keys instead.

2 Likes