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

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?

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)

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:

timer.performWithDelay( 2000, removeCircle)

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 display.contentHeight?

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

views:1429 update:2011/10/6 9:28:12
corona forums © 2003-2011