Passing parameters to a runtime event listener?

Okay so I have a game in which I use this function in a runtime listener:

 

local function moveenemy(target) if(target.direction=="left") then target:setSequence("left") target:setLinearVelocity(-30,0) else target:setSequence("right") target:setLinearVelocity(30,0) end end

And I use a runtime listener to pass all my game enemies as parameters like:

 

Runtime:addEventListener("enterFrame",function() moveenemy(enemy1) end) Runtime:addEventListener("enterFrame",function() moveenemy(enemy2) end)

So now when enemy is dead and I need to remove its listener, how do I remove it. Apparently the following doesnt work: 

 

Runtime:removeEventListener("enterFrame",function() moveenemy(enemy1) end) Runtime:removeEventListener("enterFrame",function() moveenemy(enemy2) end)

Thanks.

You should use function names instead
local function moveEnemy1()
moveenemy(enemy1)
end
Runtime:addEventListener(“enterFrame”, moveEnemy1)

–later
Runtime:removeEventListener(“enterFrame”, moveEnemy1)

The reason for this is that when you add an event listener, we store the event name and the address to the function in a table. When removeEventListener() runs, it looks through that table for a matching event name + function address.

When you use an anonymous function in the addEventListener it will generate an address for that function. When you turn around to remove it, Lua see’s a different address because it creates a new anonymous  function.  You can never remove a listener if you used anonymous functions.

Rob

okay so I need to write separate function to move each enemy. I thought maybe I could pass the enemies as parameters to a generic function.

Thanks!

You should use function names instead
local function moveEnemy1()
moveenemy(enemy1)
end
Runtime:addEventListener(“enterFrame”, moveEnemy1)

–later
Runtime:removeEventListener(“enterFrame”, moveEnemy1)

The reason for this is that when you add an event listener, we store the event name and the address to the function in a table. When removeEventListener() runs, it looks through that table for a matching event name + function address.

When you use an anonymous function in the addEventListener it will generate an address for that function. When you turn around to remove it, Lua see’s a different address because it creates a new anonymous  function.  You can never remove a listener if you used anonymous functions.

Rob

okay so I need to write separate function to move each enemy. I thought maybe I could pass the enemies as parameters to a generic function.

Thanks!