I am trying to remove objects from a table by looping through it. Though the main purpose of removing objects this way is to clean up memory once a scene is destroyed but here is a demo code to demonstrate what issue I am facing.
I am spawning ten rectangles and storing reference of each spawned rectangle in rects table. I am attaching a ‘tap’ event to each rectangle so that they are removed from display and table once they are tapped. When seven rectangles are tapped, I want to remove all the rectangles from display and rects table as well. The issue is that sometimes all the rectangles are removed once I tap seven out of them randomly, but sometimes some of the rectangles are not removed.
Here is the code
local composer = require("composer" ) local scene = composer.newScene() local rects = {} local removedRects =0 local function removeAllRects() print(#rects) print("===============================================") for i=#rects, 1, -1 do print(rects[i]) if rects[i] then print("Removing"..i) rects[i]:removeSelf( ) rects[i] = nil end end rects = nil print("all rects removed") end local function removeRect( event) removedRects = removedRects + 1 print("----------------------------------") local id = event.target.id rects[id]:removeSelf( ) rects[id] = nil print("Table size") print(#rects) for i=#rects, 1, -1 do print(rects[i]) if rects[i] then print(rects[i].id) end end if removedRects == 7 then removeAllRects() end end local function spawnRects( ) for i=1, 10, 1 do rects[i] = display.newRect( display.contentWidth/2, i\*50, 20, 20 ) rects[i].id = i rects[i]:addEventListener( "tap", removeRect ) end end function scene:create( event ) -- body end function scene:show( event ) if event.phase == "did" then spawnRects() end end function scene:hide( event ) -- body end function scene:destroy( event ) -- body end scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) return scene
I am printing some messages to console to keep track of thing. What I found is bit confusing.
The table size the I am printing using #rects most of the time returns 10 but sometimes some other number after tapping a rectangle. What I expected it to return either 10 all the times when I tap a rectangle or the size should decrement by one, once a rectangle is removed. But it either returns 10 or randomly decrement.
What am I missing?