New to Lua and Gideros and have a question about classes:
function button:init()
self.texture = Texture.new("texture.png")
self.bitmap = Bitmap.new(self.texture)
self:addChild(self.bitmap)
end
-- or --
function button:init()
local texture = Texture.new("texture.png")
local bitmap = Bitmap.new(texture)
self:addChild(self.bitmap)
end
Let me see if I understand this correctly:
'self.texture' and 'self.bitmap' would be tables that belong to the button class?
'local texture' and 'local bitmap' are variables that belong to the 'function button:init()'?
They both appear to work, so what is the better method and why? Or maybe I just got this all wrong?
Thanks in advance for the help!
Comments
I don't think the second works, because self.bitmap does not exist.
Should be the following instead :
The difference is that the first version allows you to keep an easy access to the texture and the bitmap outside of the function, which is not possible in the second case.
Understanding that subtlety means a lot.
You can learn more by studying the following link : Scope Tutorial at lua-users.org.
So you need to know which variables you are going to need again, later.
- to enjoy more flexibility, you see I gave the texture as a parameter to your button init().
- In this case I didn't need to do anything with tempCount, but as you can see this is not necessarily something that I am going to need later so it makes sense to keep it local.
That belong to the instance of the button class you are creating. I would not say that "belong" is the right word. The scope of those variables is local to the init() function which means they are not accessible from outside of the init() function.Do those answers cover your questions?
[Please someone correct me if/where I'm wrong]
In most cases, if you need to use the value stored in variable in other methods, etc you store it as self.property
but if you just create and forget about it, then you can make it local
oops, yep that second one was supposed to be 'self:addChild(bitmap)'... typo.
Thanks a lot for the thorough explanation... I'm starting to grasp the scope concept.
Just found this thread and I understand the difference between .self and local.
I do have one question tho ...
I have some sprites that I need to assess between functions, yet other just sit there.
Is there any downside / performance issues in setting everything as self. ?
Should I still be setting the ones I don't need to local?
Thank you in advance!