Remove a Group if it exists

This has been driving me mad today and there is probably a simple solution that am missing.

I basically want to remove a group of icons from the screen but they might not yet have been created. Depends what the user did before clicking to next screen.

So I tried -

myGroup:removeSelf()

Get a error if the group doesn’t exist, so put this around it -

if myGroup ~= nil then

Got rid of the error but can not get rid of the group. I even put a print statement inside the if and it doesn’t print.

if myGroup ~= nil then  
 print("am in the IF statement")  
 myGroup:removeSelf()  
end  

Am confused. If I remove the if statement, I get a error on the removeSelf, saying myGroup doesn’t exist.

Dave [import]uid: 117617 topic_id: 22740 reply_id: 322740[/import]

You can use :

display.remove(myGroup)  

The only difference between display.remove and removeSelf is that display.remove first checks if the object is not nil before trying to remove it [import]uid: 84637 topic_id: 22740 reply_id: 90732[/import]

Ah, cheers for that.

Dave [import]uid: 117617 topic_id: 22740 reply_id: 90734[/import]

@Danny, how different is

 display.remove(myGroup)  

from

if myGroup~=nil then  
 myGroup:removeSelf()  
end  

I believe that the Ansca documentation suggests that display.remove(myGroup) is in fact doing exactly the same things as if myGroup~=nil then myGroup:removeSelf() end

[import]uid: 3826 topic_id: 22740 reply_id: 90737[/import]

You can run a test like this to see the difference :

  
local myObject = display.newRect(100, 100, 100, 100)  
local function removeObjects()  
 display.remove(myObject)  
end  
  
timer.performWithDelay(500, removeObjects, 0)  

Vs

local myObject = display.newRect(100, 100, 100, 100)  
local function removeObjects()  
 if myObject ~= nil then  
 myObject:removeSelf()  
 end  
end  
  
timer.performWithDelay(500, removeObjects, 0)  

[import]uid: 84637 topic_id: 22740 reply_id: 90739[/import]

Thanks @Danny now that you have changed your response with a sample, that is much better in terms of explaining.

So I am editing my response to that too… [import]uid: 3826 topic_id: 22740 reply_id: 90740[/import]

I hit save too quickly, and whilst editing it looked bad.

I meant to say “To elaborate on my post above further”. The joys of multitasking :stuck_out_tongue:

These things happen, no worries :slight_smile: [import]uid: 84637 topic_id: 22740 reply_id: 90742[/import]