Error removing elements from array while iterating

I have the following code and I try to remove an element from the array but it doesn’t work.
I search on the forum but without luck.

Do you guys have any idea why is not working? Is this a bug or something?

Thank you!

[code]
display.setStatusBar(display.HiddenStatusBar)

local screen_w, screen_h = display.contentWidth, display.contentHeight
local background = display.newImage(“game-bg.png”,true)
local speed = 4

background.x = screen_w / 2
background.y = screen_h / 2

local cars = display.newGroup()

function carSpawn()
local car = display.newImage(“jeep-green.png”,-100,178)
cars:insert(car)

timer.performWithDelay(math.random(500,1500),carSpawn)

print(“carSpawn()”)
end

function carDespawn(i)
cars[i]:removeSelf()
cars:remove(i)

print(“carDespawn(” … i … “)”)
end

function handlerFrame()
for i=1,cars.numChildren do
cars[i].x = cars[i].x + speed

if cars[i].x > screen_w + 50 then
carDespawn(i)
end
end
end

Runtime:addEventListener(“enterFrame”,handlerFrame)

carSpawn()

–TERMINAL ERROR:
–Runtime error
–main.lua:30: attempt to index field ‘?’ (a nil value)

[/code] [import]uid: 8241 topic_id: 14949 reply_id: 314949[/import]

this is because you trying to store objects in displayGroup, rather than in a table

i can share some code, if you need, just ask [import]uid: 16142 topic_id: 14949 reply_id: 55199[/import]

The first thing that comes to mind when I see a sentence like that, “Error removing items from an array…” are many of my students who make the same mistake in their programming class.

For a detailed explanation, have a look here.

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 14949 reply_id: 55244[/import]

@jayantv that’s a very good article! thanks a lot! I removed the item backwards and it’s working now :smiley:

Thank you guys! [import]uid: 8241 topic_id: 14949 reply_id: 55317[/import]