So far, we have touched on the vital basics of programming in Lua and the terminology used in Corona SDK. Once you start developing interactive applications to sell in the App Store or Android market, you need to be aware of your design choices and how they affect the performance of your application. This means taking into consideration how much memory your mobile device is using to process the application. Here are some things to look for if you're just starting out with Corona SDK.
In some of our earlier examples, we used global variables in our code. Cases like those are an exception since the examples did not contain a high volume of functions, loops to call out to, or display objects. Once you start building a game that is heavily involved with function calls and numerous display objects, the local variables will increase performance within your application and be placed on the stack so that Lua can interface them faster.
The following code will cause memory leaks:
-- myImage is a global variable myImage = display.newImage( "image.png" ) myImage.x = 160; myImage.y = 240 -- A touch listener to remove object local removeBody = function( event ) local t = event.target local phase = event.phase if "began" == phase then -- variable "myImage" still exists even if it's not displayed t:removeSelf() -- Destroy object end -- Stop further propagation of touch event return true end myImage:addEventListener( "touch", removeBody )
The preceding code removes myImage
from the display hierarchy once it is touched. The only problem is that the memory used by myImage
leaks because the myImage
variable still refers to it. Since myImage
is a global variable, the display object it references will not be freed even though myImage
does not display on the screen.
Unlike global variables, localizing variables helps speed up the look-up process for your display object. It also only exists within the block or chunk of code that it's defined in. Using a local variable in the following code will remove the object completely and free memory:
-- myImage is a local variable local myImage = display.newImage( "image.png" ) myImage.x = 160; myImage.y = 240 -- A touch listener to remove object local removeBody = function( event ) local t = event.target local phase = event.phase if "began" == phase then t:removeSelf() -- Destroy object t = nil end -- Stop further propagation of touch event return true end myImage:addEventListener( "touch", removeBody )