removeSelf and accessing inside the loop

Beginner question again.

So I displayed an image inside a function and now I want to remove it when another function is called. But the image is local.

I declared it as local outside of the function as well but I can’t seem to access it, to remove it or make it not visible or do anything to it.

How do I access it from outside?

Thanks [import]uid: 8192 topic_id: 1775 reply_id: 301775[/import]

When you create an image using newImage, it is added to the stage. When you want to remove it, either you need to have a reference to the image, or find it in the stage object. In the simple case you need the reference. If you have a local outside of the function, make sure it has a different name than the local inside the function (so that they are different references) but maybe you don’t need the local inside the function. If you are still having problems, can you post some code?
[import]uid: 54 topic_id: 1775 reply_id: 6686[/import]

Hey Eric,

I’m having a similar issue to amigoni. I just want to create a circle and then a physics body. When the circle get’s to a certain point, I want to remove it from stage/memory.

But when I run the code below, I get a runtime error, “attempt to compare nil with number”.

Do you have any idea what’s going on?

[lua]local myCircle = display.newCircle(100, 100, 30)
myCircle:setFillColor(128, 128, 128)
myCircle.x = 100; myCircle.y = 100

local physics = require(“physics”)
physics.start()

physics.addBody(myCircle, {density=2.7, friction=0.5, bounce=0.3})
myCircle:applyForce( 250, -4000, myCircle.x, myCircle.y )

local function removeCircle(event)
if(myCircle.y < 300) then
myCircle:removeSelf()
end
end

Runtime:addEventListener(“enterFrame”, removeCircle)[/lua] [import]uid: 29663 topic_id: 1775 reply_id: 19657[/import]

That circle is disappearing as soon as you created it since removeCircle is going to fire on the next frame update. It’s deleting the circle but too fast for you to see.

And unless you remove the enterframe event listener it’s going to keep firing and attempt to remove myCricle which has already been removed. That’s causing it to get an error when you compare myCircle.y with 300, since myCircle.y is nil - it was already removed.

Comment out your eventlistener line and replace it with:

[lua]timer.performWithDelay( 2000, removeCircle)[/lua] [import]uid: 11393 topic_id: 1775 reply_id: 19710[/import]

I guess the root issue is…how do you remove an object once it’s fallen out of the visible screen?

In my code, I was using 300 as an arbitrary number, but what if I want to remove something that’s fallen past [lua]display.contentHeight[/lua]?

My first inclination would be to listen for when it falls out of bounds…

[import]uid: 29663 topic_id: 1775 reply_id: 20510[/import]