Removal of game objects - errors using object:removeSelf()

Getting to grips with Lua, I’ve created games that work! but keep getting errors when removing game objects I’ve created. Here’s the simplest example where I’m a looping through simple display objects, decreasing their timers and scaling, everything is fine until I I trying to remove, I get an error.


– animate the graphic elements that make up a slash
– call in GameLoop NOT just at event touch

local function animateSlash()

for i=1, (slashLayer.numChildren) do

local object = slashLayer[i]

if object.timer > 1 then

object.timer = object.timer -1
local t = object.timer /10
object.xScale = t
object.yScale = t
else

–kill the object
object:removeSelf()

–slashLayer:remove(i) --tried this way but still same issues
end

end
end

I get this “attempt to index local ‘object’ (a nil value)”

I have setup game objects and added them to the slashLayer group, all the objects in the game behave as expected (animation, movement, basic game logic) until I remove them…

From a programming perspective I guess the removed object is throwing off the loop, so how do I do this? I can’t see any game examples in the docs where game objects are removed.

All help greatly appreciated, I’m stuck right now!!!

[import]uid: 3093 topic_id: 8773 reply_id: 308773[/import]

Updated: I’ve changed timer to mytimer but still have the same issues when removing objects in a loop [import]uid: 3093 topic_id: 8773 reply_id: 31984[/import]

Below this:
for i=1…
Try to add the following to wrap the code afterwards:
if slashLayer[i] ~=nil then … end

I guess it’s because after an object has removeSelf(), slashLayer still has reference to it as an element, so in next loop, deferencing a nil object gives you this “a nil value” error. Hope it helps.

[import]uid: 11385 topic_id: 8773 reply_id: 32066[/import]

That worked! Thanks gamehkmail ! I had previously tried a if slashLayer == True test but that didn’t work.

I’m finding Corona a very fast and powerful and making great progress considering I have little high level language experience, great fun with instant results.

[import]uid: 3093 topic_id: 8773 reply_id: 32073[/import]

You’re welcome. :smiley:
– Advanced UI + Graph for Corona® | Website | Forum (https) | See: [import]uid: 11385 topic_id: 8773 reply_id: 32633[/import]