Properly Removing Objects

I’m making a game where you play as a man and you must dodge blocks falling from above. I want to make the blocks remove themselves when they reach a certain height, so I created the following code to spawn and control a block. It seems to work correctly, but I’m not sure if the blocks are being completely removed… How can I tell? Can anyone tell if I’m removing them correctly? Any other advice would also be great!

--Spawn Box--------------------------------------------------------------------------------------  
local function spawnBox()  
 local box = display.newRect(mRand(0, 9) \* (pixelSide\*8), -pixelSide\*6, pixelSide\*7, pixelSide\*7);  
 setColor(box, mRand(0, 7));  
  
 function box:enterFrame(event)  
 self.y = self.y + pixelSide;  
  
 if (self.y \>= \_H-(pixelSide\*19.5)) then  
 self:removeSelf();  
 Runtime:removeEventListener("enterFrame", box);  
 box = nil;  
 self = nil;  
 end  
 end  
  
 Runtime:addEventListener("enterFrame", box);  
end  
-------------------------------------------------------------------------------------------------  

The variable pixelSide is 1 80th of the screen’s width so that the game looks the same on all devices.

The function setColor merely sets the box’s color based on the random value passed to it.

Thanks in advance for all your help! [import]uid: 90817 topic_id: 17624 reply_id: 317624[/import]

self = nil doesn’t usually make the object nil, since the object was used to call the function.

Perhaps create a forward declaration so another code block can access the object, and nil it out if removeSelf() is called (or have the block that calls removeSelf() call an external function that nils out the object’s variable. [import]uid: 52430 topic_id: 17624 reply_id: 67091[/import]

I was wondering, does a display object automatically remove itself if the group it’s in calls removeSelf()?

Also, is the memory used by a variable automatically recycled when the block of code it was created in terminates? [import]uid: 90817 topic_id: 17624 reply_id: 67145[/import]

  1. Yes
  2. It depends on how you have your cleanup function [import]uid: 84637 topic_id: 17624 reply_id: 67220[/import]