Reputation: 63
local function myInit()
local topBackGround = display.newImageRect("backGround.png", 500, 500)
topBackGround.x = 0
topBackGround.y = 0
end
as i know local variable will not using memory after we jump out the function, as this case the image still exits, will it using memory ?
if no, what if i insert it to a global displayGroup ?
Upvotes: 0
Views: 149
Reputation: 473577
Lua is garbage collected. So it will still exist until Lua collects it. Since nobody has a reference to the object anymore, it can be collected anytime after the function exists.
However, the fact nothing has a reference to the object means that you couldn't use it anyway. You could create a new one, but it would be a new object, not the same one as before. Now, because Corona caches images, it may internally refer to the same image if the original wasn't collected. But it's terribly bad form to do this.
Anytime you create something in Lua, if you want to keep it around, then you need to actually keep it around. Keep a reference to it.
Put it another way. This:
display.newImageRect("backGround.png", 500, 500)
Returns a value. A unique value. Any variables declared local
are discarded after their scope ends (unless they are captured by functions as closures).
If at any time, your program cannot find a value, because all references to it are discarded, then that value will be eliminated. Therefore, if you want to be able to use something, you need to keep it in a place where you can get at it. Otherwise, Lua knows you can't find it and will delete it.
Upvotes: 1