help removing object from enemies created in a loop please

I have created a set of 4 enemies each with a different loop ,enemy, enemyPurple, enemyRed and enemyYellow.

The creation code is the same for each. example below:

SORRY ABOUT THE FORMATTING THE LUA TAGS ARE NOT WOKING PROPERLY AGAIN,

enemy = {}
    local b = 1

    for y = 1, 3 do
        for x = 1, 10 do
            enemy[b] = display.newRect( layer, 0, 0, 15, 10)
            physics.addBody(enemy[b], { isSensor = true, filter = filtersModule.enemyFilter })
            enemy[b].isVisible = true
            enemy[b].isBodyActive = true
            enemy[b].name = “enemy”
            enemy[b].collision = onCollision
            enemy[b]:addEventListener(“collision”, enemy)
            enemy[b].x, enemy[b].y = posXfront[x], posYfront[y]
            enemy[b].x0 = enemy[b].x
            enemy[b].y0 = enemy[b].y
            b = b + 1
        end
    end

Now I am trying to remove them with a global collision listener:

function onCollision(event)
        if event.phase == “began” then

            if event.object1.name == “enemy” or event.object1.name == “enemyPurple” or event.object1.name == “enemyRed”
                   or event.object1.name ==“enemyYellow” and event.object2.name == “bullet” then
                print(“collision”)
                timer.performWithDelay(10, function()event.object1:removeSelf()      event.object2:removeSelf()event.object1 = nil
                                        event.object2 = nil end)

            end

            end
    end
    Runtime:addEventListener(“collision”, onCollision)

my problem is I am removing the whole enemy with the code above and get errors in the movement function.

So I tried :

 table.remove(enemy, table.indexOf(event.object1))
               event.object1:removeSelf()

event.object1 = nil

event.object2:removeSelf()

event.object2 = nil   ----bullets are not in a table

I had no joy with this but if I put it in a table listener it works, so why is it not working in a global collision listener ?

I would prefer to handle it globally.

Thank you

You say: “my problem is I am removing the whole enemy with the code above and get errors in the movement function.”

Could you post your movement function?

My guess (only a guess since I haven’t seen the code) is that the movement is done with a transition.to that calls itself and never gets cancelled… so once the enemy is removed then the transition has nothing to move.  I might be way off though.

You say: “my problem is I am removing the whole enemy with the code above and get errors in the movement function.”

Could you post your movement function?

My guess (only a guess since I haven’t seen the code) is that the movement is done with a transition.to that calls itself and never gets cancelled… so once the enemy is removed then the transition has nothing to move.  I might be way off though.