Why does the #table does not return the accurate value of the table's length?

  1. What do I want to achieve?

I wanted to make it so this piece of code should return me 1

local MAPS = {
	Grassland = serverStorage:WaitForChild("Maps"):WaitForChild("Grassland"), -- Grassland
}

print(#MAPS)
  1. What is the issue?

Eventhough the table has 1 value, the output keep print 0
image

BUT if I changed from that value to this one:

local MAPS = {
	1,
}

Now it prints 1
image

  1. What solutions have you tried so far?

Well, for this one, I don’t even know if there is anything possible way to debug so no? I guess?

# does not work for dictionary style tables IIRC.

The length operator for tables does not account for string-indexed entries in itself. You can just use an array instead, like so:

local MAPS = {
    {Grassland = serverStorage:WaitForChild("Maps"):WaitForChild("Grassland")}
}

Or just make your own function to count the number of entries in the table, including string-indexed entries by iterating over all of the elements with pairs:

local function count(tbl)
    local total = 0

    for index, value in pairs(tbl) do
        total = total + 1
    end
end
1 Like