Array size

4

How do I get the size of an array with this structure:

A = {
    ["b"] = {c=1, d=2},
    ["e"] = {f=1, g=2},
}

I want to get the size of A, in this case, 2.

    
asked by anonymous 21.09.2014 / 08:04

1 answer

6

Moon has tables and not arrays . Lua tables have array semantics and hash semantics depending on how you put their elements in, and this can be a bit confusing.

An array must have a sequential integer index, preferably starting at 1. The size is defined by the number of elements. If really is an array and start at 1, we know that the highest index matches the size of the table. But what you are trying to check in the example is the size of a hashs structure and not an array .

You have some possible solutions depending on your goal.

table.getn(A)

or

#A

This is the most obvious solution but it may bring different results than you expect if you have some nil element in the middle of the table. It counts the number of elements until you find a nil . The second is the length operator. If you can guarantee that you have an array and not a hash this might work.

table.maxn(A)

This form returns the highest possible index in the table. It may be the solution you want depending on the constitution of the table. If it does not contain null elements in the table this is confused with the total elements. Works best for tables that are hashs . It is not the focus of the title of your question but it is what you are actually using. You have primarily a hash and not an array . It's good to understand the difference.

function table.map_length(t)
    local c = 0
    for k,v in pairs(t) do
         c = c+1
    end
    return c
end

This algorithm counts all elements in a table that can have arbitrary indexes. It also works fine for hashs . These solutions can be more guaranteed if you are not absolutely sure that you have an array on hand. Font .

Test with your example on ideone . I do not put examples from others because they will not return the expected result for your example.

function table.map_length(t)
    local c = 0
    for k,v in pairs(t) do
         c = c+1
    end
    return c
end

A = {
["b"] = {c=1, d=2},
["e"] = {f=1, g=2},
}

print(table.map_length(A))

See running on ideone . And at Coding Ground . Also I placed it on GitHub for future reference .

    
21.09.2014 / 11:07