Length of a table

When using the


function how does it determine the length of a table
For example I have a table called touches which I add to using

If touch.state == BEGAN then
    touches[touch.id] = touch

But the length of the table does not change. Is this because codea looks for the fist item in the table without anything after it to find the length? How can I solve this problem?

@Jazmal you dont define the indexes in your table, so by default they are 1 to n. This is why maxn (or #) works.


“return the largest positive numerical index of the given table, or zero if the table has no positive numerical indices”

so, in your case 66

but per example:

function setup()
   tst = {
      [0] = 3,
      [6] = 3,
      tst = 3,
      [12] = 3
   print(table.maxn(tat)) -- result 12

it a a very common newbee problem with lua. Check the web.

i checked the web, but no clear answer. So here it is:
#table gives you the number of indexes starting at 1, up to n, with no interruption. Your Touch.id is not an simple integer, so it is not counted. To know the number of elements of your table, count it youself with:
n=0; for i,v in pairs(table) do n=n+1 end.
No other way.

ok thanks, so if I had a table


The length would be 1


also note that the order is kept only for those 1 to n, without inturruption. Other indexes can come in any order.

Could you use the table.maxn(table) to find the number of records

Here is a simple function that will return how many items are in a table:

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

    return count

Thanks for the help guys

@HyroVitalyProtago thanks for correcting my mistake!

i dont think so: maxn is also for consecutive integers (i think).

Using table.maxn will tell you how many fields in table.
Example shows a 6 * 11 table array run the below sample will print out the result. In this case 66

Hope this helps

-- Maxn

-- Use this function to perform your initial setup
function setup()
    print("Hello World!")

-- This function gets called once every frame
function draw()
    -- This sets a dark background color 
    background(40, 40, 50)

    -- This sets the line thickness
    print (table.maxn(bulkmod))
    -- Do your drawing here