Length of a table

When using the

#table

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
End

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.

table.maxn:

“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
end

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.

@Jmv38
ok thanks, so if I had a table

{[1]=a,[3]=b,[5]=c}

The length would be 1

exactly.

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
    end

    return count
end

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!")
    bulkmod={
    "0","0","0","0","0","0",
    "0","0","0","-4","-4","0",
    "0","0","0","-2","-1","0",
    "0","0","0","-1","0","0",
    "0","0","0","0","1","0",
    "-4","0","-4","1","2","0",
    "-3","-4","-3","2","3","-3",
    "-2","-3","-2","3","4","-3",
    "-1","-2","-1","4","5","-2",
    "0","-1","0","5","6","-2",
    "3","0","1","6","7","0"}
end

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

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