Length


We discussed Lua's length operator in the context of lists and strings. Now let's take a look at finding the length of a map.

Let's first take a look at how the length operator behaves with a map:

local x = {
    a = 1,
    b = 2,
    c = 3,
    d = 4,
    e = 5,
}

print(#x) -- 0

Hmm, that was not expected. The table clearly has 5 values in it, but the result is 0. It turns out the that length operator only considers the number of list-like values contained in a table, and does not consider mappings at all.

Getting the number of items in a map requires counting items manually:

local count = 0

for key, val in pairs(x) do
    count = count + 1
end

print(count) -- 5