I almost 100% of the time store objects in tables by their ids, then maintenance is easy. I only use numerically indexed tables for special cases or where order is paramount.
Example:
-- Semi-elaborate example showing some very important principles for reducing your memory footprint -- and for maintaining clean code. local physics = require "physics" physics.start() physics.setGravity(0,0) local objCountTarget = 10 local myObjects = {} local countObjs() local count = 0 for k,v in pairs(myObjects) do count = count + 1 end return count end -- unified collision handler local function onCollision( self, event ) myObjects[self] = nil self:removeEventListener("collision") display.remove(self) return false end local randomMaker() local x = math.random(-300,300) local y = math.random(-300,300) local tmp = display.newCircle( x, y, 10 ) physics.addBody( tmp ) -- store in table by object ID myObjects[tmp] = tmp tmp.collision = onCollision tmp:addEventListener( "collision" ) -- not great to mix transitions with physics, but doing so for this example to keep simple transition.to( tmp, { x = display.contentCenterX, y = tmp.contentCenterY } ) end local function enterFrame() if( countObjs() \< objCountTarget ) then randomMaker() end end Runtime:addEventListener( "enterFrame", enterFrame )
Assuming this example has no syntax errors, it will strive to keep 10 circles on the screen, taking 10 frames to get there, but subequently keeping it so every frame (except in the case where removals happen in the same frame).
These circles will appear randomly on the screen and move to the middle.
When circles touch, they self delete, using a common collision Listener.
This code is fast, clean, and will not leak