Table Length

Does anybody Know how to get the length of a table?
Thanks

A LUA table t is a set of key, value pairs where neither key nor value can be nil
If the table contains numeric keys 1,2,…,n but not key=n+1,
that part is considered to be an array.
#t gives the length n of the array part.
The following code gives the number of keys not in the array part, if any:

function CountTableKeysNotInArrayPart(t)
     i=0
    for k,v in pairs(t) do
        i = i + 1
    end
    return i-#t
end

Here’s a function :

table.count = function(tbl) 
    local count = 0
    for foo, bar in pairs(tbl) do
        count = count + 1
    end

    return count
end

use it like so: print(table.count(tab))

number of elements is tricky in lua. I have already explained on the forum. Try google search, which give for instance:
http://stackoverflow.com/questions/2705793/how-to-get-number-of-entries-in-a-lua-table

Ok. thanks!

@RonJeffries
So print(#tab) would print out the length of the table?

Yes

It depends on what’s in the table. The table tab has 9 entries, but #tab shows 7.


function setup()
    tab={1,2,3,4,a=5,b=6,7,8,9}
    print(tab.a)
    print(tab.b)
    print("size ",#tab)
end

it tab is a table, i believe #tab will do the job

Here’s a function that will return the count of numeric and alpha keys.


function setup()
    tab={1,2,3,4,aa="one",bb="two",7,8,9,cc="three",dd="four",ee="five"}
    print(count(tab))
end

function count(t)
    local num,alp=0,0
    for a,b in pairs(t) do
        if type(a)=="number" then
            num=num+1
        else
            alp=alp+1
        end       
    end
    return num,alp
end

If you have a large table where you are adding and/or deleting all the time, you may not want to be running a loop every frame to figure out the size of the table.

So an alternative is to use a counter to keep track of the size.

If you want to count the entries in a multi dim table.


function setup()
    tab={}
    
    for z=1,10 do   -- create a multi dim table
        table.insert(tab,
        {   
        name="qwerty",name1={n1="asd",n2="zxcv"},
        addr={addr1="12345",addr2="45678"},
        city={city1={city1a="aaa",city1b="bbbb"},city2={"zzzzz","sdfgh"}},
        state="asdfg",
        } )
    end
    
    print("table size using # ",#tab) 
    print("actual table size "..count(tab,0))
end

function count(t,a)
    if a==0 then
        tabSize=0
    end
    for a,b in pairs(t) do
        if type(b)=="table" then
            count(b,1)
        else
            tabSize=tabSize+1
            --print(a,b)    -- uncomment to print entries
        end
    end
    return tabSize
end