Checking values within tables

Hello everyone,

Assume I create a simple function that randomly generates a ball to be located on one of three floors. Like so:

  
balltable = {}  
  
local function spawnball()  
 local i = math.random (3)  
  
 local ball = display.newImage("Ball.PNG")  
 allballs[#allBalls+1] = ball  
   
 ball.floor = i  
 ball.x = 100 x i  
  
end  
  

How would I go about writing a function that checks whether balltable contains a ball with “ball.floor” having a certain value. For example, lets say there are three buttons that correspond to each floor and the user must press a button for a floor that has a ball on it. How would the function associated with the button check whether there is a value in balltable with ball.floor = 3

I hope my hypothetical example is clear enough. I’m trying to learn how to search values in tables. [import]uid: 78150 topic_id: 20894 reply_id: 320894[/import]

ggortva,

This is how I’d do it. I’m guessing you mean “balltable” rather than “allBalls” in your population loop? I -think- this should work.

[lua]–Pass in floor to check.
–Returns true if a ball on this floor, otherwise returns false.
local function ballOnFloor(floor)
local i
for i = 1, #balltable, 1 do
if ( balltable[i].floor == floor ) then
return true
end
–No ball found on this floor, so return false.
return false
end

–And call like this
if ( ballOnFloor(3) ) then
–Do something
end[/lua] [import]uid: 22076 topic_id: 20894 reply_id: 82381[/import]

thats perfect, thanks! [import]uid: 78150 topic_id: 20894 reply_id: 82470[/import]