Local variables and methods in object factory module

Hi.

The following example shows (I hope) the method I’m using for making a module that can create/return viewGroup objects.

Inside the new() method I create local methods and vars (speed). I add an enterFrame listener that calls a local method. I also create a new viewGroup and return it.

The part I cannot get my head around is why and how my returned viewGroup object has knowledge of the local variable speed and the other local methods. I never add any references to them in viewGroup - so how?

If I create more viewGroups by calling new() each one will output a different speed in their onEnterFrame. This tells me each viewGroup must have speed set as a local private variable.

Is this true? - or what is going on here?

Any help as very welcome - thanks :slight_smile:


In file “factory.lua” I have the following:

[lua]local factory = {}

function factory:new()

local addListeners – forward method declaration
local onEnterFrame – forward method declaration

local speed = math.random(1,10)
local viewGroup = display.newGroup()

addListeners = function()
Runtime:addEventListener(“enterFrame”, onEnterFrame)
end

onEnterFrame = function()
print(“enterframe called - speed”, speed)
viewGroup.x = viewGroup.x + speed – move viewGroup
end

addListeners()

return viewGroup

end

return factory [/lua]
[import]uid: 87555 topic_id: 18668 reply_id: 318668[/import]

Have a read of these; they will broaden your knowledge of modules and hopefully answer any questions you have. (They’re very thorough.)

http://blog.anscamobile.com/2011/09/tutorial-modular-classes-in-corona/
http://blog.anscamobile.com/2011/07/using-external-modules-in-corona/
http://blog.anscamobile.com/2011/09/a-better-approach-to-external-modules/

Peach :slight_smile: [import]uid: 52491 topic_id: 18668 reply_id: 71784[/import]

Thanks Peach Pellen for the fine links.

However, after reading through them and after having a good nights sleep I realized what I’m actually doing in my example is using Closures - the Object Oriented Closure Approach. The factory:new() function is actually a closure - things make a lot more sense to me now.

I think the following link describes it quite well:
http://lua-users.org/wiki/ObjectOrientationClosureApproach

[import]uid: 87555 topic_id: 18668 reply_id: 71955[/import]