Remove an object, before displaying the same object

I have a function where when you press a button an image is displayed. I would like to, when the user presses the button again, to remove the image, then display it again, so a bunch of them dont pile up.

I could only get it working so far with a global, and calling display.remove at the start of the function. How could I use a local to do this?

local function animate( event )
 
display.remove( image )

local physics = require( “physics” )

physics.start()

local ground = display.newImage( “ground.png”, 75, 200 )

physics.addBody( ground, “static”, { friction=0.5, bounce=0.3 } )

image = display.newImageRect( “1.png”, 90, 100 )
    image.x = 100
    image.y = -85

physics.addBody( image, { density=3.0, friction=0.5, bounce=0.3 } )
    
end

Hi Betlic,

It’s basically OK to use a local up-value reference to the object, and then “display.remove()” it just like you are doing now. That will remove the object from the display but its internal reference will still exist so you can immediately apply a new display object to the same reference.

Brent

I see, so what Im doing is along the similar lines such as this, where ‘mask’ is not local.

-- Create up-value reference for mask local mask -- Check the image suffix values and pick the correct mask if ( display.imageSuffix == "@4x" ) then --print( "using @4x" ) mask = graphics.newMask( "circlemask@4x.png" )

Well yes, basically, but in that code, “mask” is local. You can do the same thing in your code, assigning an image to the up-value reference, display.remove()-ing it later, then assigning a new image to the same variable.

Brent

Nice. Thank you for explaining that.

Hi Betlic,

It’s basically OK to use a local up-value reference to the object, and then “display.remove()” it just like you are doing now. That will remove the object from the display but its internal reference will still exist so you can immediately apply a new display object to the same reference.

Brent

I see, so what Im doing is along the similar lines such as this, where ‘mask’ is not local.

-- Create up-value reference for mask local mask -- Check the image suffix values and pick the correct mask if ( display.imageSuffix == "@4x" ) then --print( "using @4x" ) mask = graphics.newMask( "circlemask@4x.png" )

Well yes, basically, but in that code, “mask” is local. You can do the same thing in your code, assigning an image to the up-value reference, display.remove()-ing it later, then assigning a new image to the same variable.

Brent

Nice. Thank you for explaining that.