why is sceneGroup not working when i have an image spawn in a function?

So i when my game scene starts a ball is spawned and when i click that ball it disapears and then my function is supposed to start… that function is - a ball spawns and when i click it the ball dissapears… but when i try to remove the ball with display.remove(ball) is gives an error that the ball isnt there… so what im thinking is that the sceneGroup doesnt work in the function? heres the function…

 local circle2 = {} local counter2 = 1 local function spawnCircle2(event) if event.phase == "began" then local spawn = math.random(display.contentWidth \* 0.1, display.contentWidth \* 0.9) local spawn2 = math.random(display.contentHeight \* 0.01, display.contentHeight \* 0.99) circle2[counter2] = display.newImageRect( "circle.png", 40, 40 ) circle2[counter2].x = spawn circle2[counter2].y = spawn2 circle2[counter2].value = counter2 counter2 = counter2 + 1 sceneGroup:insert(circle2[counter2]) print("TEST4") end return true end 

and when i try to add a event listener like this

circle2:addEventListener("touch", spawnCircle2) BUT Runtime:addEventListener works..

then is says it cant add an event listener to circle2  because its not there…

Any ideas on whats wrong? and what could be fixed? Thanks!

Issue #1 might be due to scope. Is your  sceneGroup  declared prior to your creation of the above function? If not, then your function might have problems adding objects to the display group. 

Issue #2a, it appears you are creating a table of objects in the above function. That table is  circle2. If you want the touch listener to correspond to all of your objects, then you need to include the touch listener lines inside of the function itself,when you are creating the display object which should possess the listener. 

Issue #2b. You are increasing the count for your circle2[i] object before you add it to the sceneGroup. You might want to move your  counter2 = counter2+1  line to the last operation that happens inside of that function.

Issue #1 might be due to scope. Is your  sceneGroup  declared prior to your creation of the above function? If not, then your function might have problems adding objects to the display group. 

Issue #2a, it appears you are creating a table of objects in the above function. That table is  circle2. If you want the touch listener to correspond to all of your objects, then you need to include the touch listener lines inside of the function itself,when you are creating the display object which should possess the listener. 

Issue #2b. You are increasing the count for your circle2[i] object before you add it to the sceneGroup. You might want to move your  counter2 = counter2+1  line to the last operation that happens inside of that function.