# Counting concurrent touches?

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

`````` print(table.getn(touches))
``````

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

Mark

``````-- 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 = {}
end

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

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

I think the problem is getn(): i assume it works when table is a=…, a=… etc, but the index used for touches[] is touch.id, which is not at all 1,2,3 but a very complex number (very high). Try to print(touch.id) 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[touch.id] = nil
else
self.touches[touch.id] = touch
end
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
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.