Printing the number of items inside a table returns 0

Hey there, I was just making myself a music player when I suddenly came to a problem where the number of items inside a table is 0 when it’s actually not.

Example script:

local table = {
    ["a"] = 1,
    ["b"] = 2,
    ["c"] = 3
}

print(#table)

This should be printing 3 but prints 0, why?

When you use the hashtag syntax followed by a table, as you have done, it doesn’t print all of the entries. Instead, it prints all the entries, and since you have 3 entries it will print as such. If you want to print everything in the table simply do table without log mode on or use a for loop with pairs or next.

The length operator (#) does not account for non-numerically-indexed entries in the table, basically an entry that has an index that is not a number, such as string, will not be accounted for by the length operator, hence why it prints zero.

You can use a generic for loop using pairs to count how many entries are in the table, regardless of whether or not the indices are not a number

4 Likes