Hi,
I just read a tutorial about scopes for functions:
http://blog.anscamobile.com/2011/09/tutorial-scopes-for-functions/
(originally posted by Jayant Varma of OZ Apps on http://howto.oz-apps.com/2011/09/scopes-for-functions.html)
In one of the examples in the ‘Member functions’ section we can find a non-localised function
[lua]resultingObject.changeColor(theColor)[/lua]
so we can use that function later in the code when we are out of scope of spawnObject function
Example:
[lua]local function spawnObject()
local resultingObject = display.newRect(10,10,100,100)
function resultingObject.changeColor(theColor)
resultingObject:setFillColor(theColor[1],theColor[2],theColor[3])
end
local function onTouch(event)
if “ended” == event.phase then
print(“touched rectangle”)
end
end
resultingObject:addEventListener(“touch”,onTouch)
return resultingObject
end
local xTemp = spawnObject()
xTemp.changeColor({255,0,255})[/lua]
On the other hand we should always try to use locals. Moreover, functions are variables too in Lua, as we can read at Lua: Best Practices section on http://developer.anscamobile.com/content/performance-and-optimization
Use locals (i.e. avoid global variables)
Avoid global variables. Period. In Lua, you will sacrifice performance if you use global variables. When in doubt, precede your variable declarations with local .
This applies even to functions. In Lua functions are variables too. In long loops, it’s better to assign a function to a local variable
As I understand, that member function (changeColor) is not local and ‘lives’ after the spawnObject() function finishes execution (and destroy all ‘nested’ locals)
Could anyone explain me
- Can using non-localised member function in that scenario affect performance?
- Can we consider that changeColor function is a global variable? If so, what about garbage collection and memory-leaks?
Cheers,
Patryk [import]uid: 51816 topic_id: 24950 reply_id: 324950[/import]