I have an array containing display objects. I’m looping through the array each frame and moving the objects across the screen. When they reach the far side of the screen, I remove the object from the array, and remove it from the display.
Here’s problem, the next frame I get an error: “attempt to index local ‘thing’ (a nil value)”. It’s like the array still has an index reserved for the object that has been removed.
I’m using the following to remove object from the array:
table.remove( thing\_array, table.indexOf( thing\_array, thing ) )
What am I missing here?
Here’s a full sample of code you can copy and paste this into a landscape project to test.
-- Define an array to hold things local thing\_array = {} local function list\_things() local str = "" for i = 1, #thing\_array do str = str .. thing\_array[i].name .. " " end print( str ) end -- Define a function to remove things local function remove\_thing( thing ) print( thing.name, table.indexOf( thing\_array, thing ), #thing\_array ) table.remove( thing\_array, table.indexOf( thing\_array, thing ) ) display.remove( thing ) end -- Define a function to make things local function make\_thing() local thing = display.newCircle( 0, 0, 24 ) thing.x = -60 thing.y = 60 thing.speed\_x = 3 thing.vy = 0 thing.gravity = 1 thing.name = "thing\_" .. #thing\_array table.insert( thing\_array, thing ) end -- This function handles enter frame events local function on\_frame( event ) list\_things() for i = 1, #thing\_array do local thing = thing\_array[i] thing.vy = thing.vy + thing.gravity thing.y = thing.y + thing.vy if thing.y \> 300 then thing.y = 300 thing.vy = -thing.vy end thing.x = thing.x + thing.speed\_x if thing.x \> 540 then remove\_thing( thing ) end end end Runtime:addEventListener( "enterFrame", on\_frame ) local thing\_timer = timer.performWithDelay( 1000, make\_thing, 0 )