object:removeSelf()

Type Function
Object DisplayObject
Library display.*
Return value none
Revision 2017.3060
Keywords removeSelf, removing objects, delete object, removal
See also display.remove()
group:remove()

Overview

Removes the display object and frees its memory, assuming there are no other references to it. This is equivalent to calling group:remove() on the same display object, but it is syntactically simpler. The object:removeSelf() syntax is also supported in other cases, such as removing physics joints in the physics engine.

When you remove a display object, event listeners that are attached to it — tap and touch listeners, for example — are also freed from memory. You don't need to explicitly remove event listeners that are isolated to the object. See the Display Objects guide for further details on object removal.

The object:removeSelf() method converts a display object into a normal Lua table that will be garbage collected if there are not other references to the object. You should also set the object to nil after removing it.

Syntax

object:removeSelf()

Gotchas

As a best practice, you should set any variables to nil after calling object:removeSelf() on it.

When an object is removed, the rendering-related resources of the removed object are deleted immediately. What remains of the object is simply a plain Lua table with all non-display object properties — the metatable is set to nil and all properties relating to display object are removed. Thus, if there are still references to object in Lua, they will simply be references to a normal Lua table.

Example

local obj = display.newImage( "image.png" )
obj:translate( 100, 100 )

-- remove the object
obj:removeSelf()
obj = nil