Counting concurrent touches?

I’m trying to count the number of concurrent touches. I’ve added the line


to the multitouch example but it doesn’t give the results I expect. Am I missing something simple here?


-- Use this function to perform your initial setup
function setup()
    print("This example tracks multiple touches and colors them based on their ID")
    -- keep track of our touches in this table
    touches = {}

function touched(touch)
    if touch.state == ENDED then
        touches[] = nil
        touches[] = touch

-- This function gets called once every frame
function draw()
    background(0, 0, 0, 255)
    for k,touch in pairs(touches) do
        -- Use the touch id as the random seed
        -- This ensures the same fill color is used for the same id
        -- Draw ellipse at touch position
        ellipse(touch.x, touch.y, 100, 100)

I think the problem is getn(): i assume it works when table is a[1]=…, a[2]=… etc, but the index used for touches[] is, which is not at all 1,2,3 but a very complex number (very high). Try to print( you’ll see what i mean. I solved the problem by counting the touches elements in the variable n below. It is like implementing my own getn() function:

function CameraControl:touched(touch)
    if touch.state == ENDED then
        self.touches[] = nil
        self.touches[] = touch
    local n = 0
    for i,v in pairs(self.touches) do n = n + 1 end
    -- if exactly one touch then move
    if n==1 then self:move(touch) end
    -- if exactly 2 touches then zoom
    if n==2 then self:zoom() end

There is not direct way to retrieve the number of elements in a table, getn (which is the length operator #, depending on the specific version of Lua) relies on a gapless sequence starting at 1 (the wording in 2.5.5 seems to allow other combinations, however).

You have to count the number of elements yourself.