In general, you do not need to “nil out” any local variables. Lua automatically destroys them out at the end of the block in which they exist. That said, the local variable reference concept can be a little twisty at times. Example:
[lua]
local function getImageThingy()
local image = display.newImage(“image.png”) – “image” is now a local reference to an image object
return image
end – “image” variable is destroyed at end of block
local myImage = getImageThingy() – Now “image” doesn’t exist, instead it’s stored in “myImage”
local myImage2 = myImage – Now both “myImage” and “myImage2” refer to the image we created in getImageThingy()
myImage = nil – Destroys the “myImage” reference, but leaves “myImage2”, so the memory isn’t freed
myImage2 = nil – The image we created now has no references to it, so its memory is freed
– We didn’t need to explicitly nil out “myImage” and “myImage2”, though; the end of their block is right here so they both would have been nil-ed out anyway
[/lua]
In the above example, you can see we twiddle around with references a lot. At the end, I say that “its memory is freed”. That’s correct… On Lua’s side. On Lua’s side, we have absolutely no access to the image, but on Corona’s side, the image is still in memory. We can’t access it, but it exists. This is the basis of a memory leak. To keep this from happening, you need to first Corona-delete the object.
So do you need to nil out local variables for the memory to be freed? No. Lua takes care of that for us. However, when you call display.remove()
or obj:removeSelf()
, the Corona-side memory and references are freed, but Lua still has access to a “shell” of the object. It’s not nil, it’s just a non-display-object thing whose memory hasn’t been freed. Example:
[lua]
local m = display.newRect(0, 0, 100, 100)
display.remove(m)
print(m) – table: 0x7ffa1489c280
[/lua]
In that example, we clearly deleted the display object… On Corona’s side. But when we print it out, we still have access to the object. If you try to use any methods on the object, you’ll get an error, but it’s still technically an object. Thus, we can’t just Corona-delete the object, instead we have to also nil it out:
[lua]
local m = display.newRect(0, 0, 100, 100)
display.remove(m)
m = nil
print(m) – nil
[/lua]
Nil-ing out display objects after they’ve been removed is mostly just a practice for maximum safety. If you never access the object again after it’s Corona-deleted, you’ll never have a problem, but if you do, all sorts of weird bugs can crop up because the object is sorta-half-not-really-deleted. If, on the other hand, you nil out your display objects after Corona-deleting them, you’ll clearly be trying to deal with a nil variable when you do anything to it. Bugs are a lot easier to fix that way, and it just overall keeps things nice and clean.
P. S. I think I coined a new phrase - “Corona-delete” :D.