How to remove a spawned object in table

So now, I create a table and spawn red boxes with time delay.

By the time when it spawns a few red boxes, (Rboxes[1], Rboxes[2], Rboxes[3])

I tried to remove the red boxes by tapping the red button.

However, I cant remove the rest of the red boxes (Rboxes[2], Rboxes[3])

My question is: What should i do to remove the rest of the boxes?

[lua]display.setStatusBar ( display.HiddenStatusBar )

require (“physics”)
physics.start()

local w = display.contentWidth
local h = display.contentHeight
local centerX = display.contentCenterX
local centerY = display.contentCenterY

local mRandom = math.random

– Ground
local ground = display.newRect ( 10, 10, 320, 10)
ground.x = centerX
ground.y = centerY - -180
physics.addBody ( ground, “static”, {friction = 0.3, bounce = 0.1} )

– Create Red btn

local Rbtn = display.newRect( 150, 450, 30, 30 )

Rbtn.x = display.contentCenterX - 130
Rbtn:setFillColor(155,0,0)

– Create tables to store new boxes in
local Rboxes = {}

– Create Red box

local function addRedbox()

     local newIdx = #Rboxes+1
     Rboxes[newIdx] = display.newRect(mRandom(w/2-100, w/2+100), -30, 30, 30)
     Rboxes[newIdx]:setFillColor(155,0,0)
     physics.addBody (Rboxes[newIdx], " static", {density = 0.1, friction = 3, bounce = 0} )
end

– Spawn boxes

function newBox ()

     rand = mRandom ( 1 )

     if ( rand < 2 ) then
     addRedbox()

     end
end

timer.performWithDelay ( 300, newBox, 4)

– Create Red btn touch event

function touchRedbtn ( event )

     if event.phase == “began” then

     display.remove (Rboxes[1])
     Rboxes[1] = nil

     return true
     end
end

Rbtn:addEventListener (“touch”, touchRedbtn)
[/lua]

for index,ref in pairs(Rboxes) do display.remove(ref) end Rboxes = {}

or if you know it’s sequential you can use an array index.

You could put them all in a group and remove that.

for index,ref in pairs(Rboxes) do display.remove(ref) end Rboxes = {}

or if you know it’s sequential you can use an array index.

You could put them all in a group and remove that.