Creating Dynamic Variables
Oooh!! Shiny!! My Pretty... I guess I generalise when I say in most of my posts, that *every developer*, but that is more or less a fact, as this has been the basics of development, and time and time again developers have asked for it and therefore it has been provided to them in various forms in the different languages. Here's how you can create dynamic variables in LUA/CoronaSDK
where the i can be a number that we do not have an idea about at this point in time. Think about it again, isn't this similar to what we call arrays? So how about
This will offer you the same functionality as what you were after, BUT... there is a small catch, if you are going by the index i, and you remove an item or add an item somewhere in between, the rest of the items in the array get all mixed up. So, how do we fix that? Easy...
Now even if you delete a particular button or insert a new button, the index will remain as buttonX and will not get renumbered.
What is a dynamic variable
In my understanding, a dynamic variable is one that is not declared while coding as I would have no clue if I need that variable in my code or not. That variable might be required later on if a particular object is created, or a particular condition is met, etc.Why do I need a dynamic variable
I am not sure what cools stuff some other developers might have in store, but I would use a dynamic variable to let's say reference a series of objects that I create. I could use that if I was writing a parser, or a IDE add-in (of course not in CoronaSDK) which might need to declare some variables based on the user's input. Let's say I was creating my own little VM or interpretter, I might want to store the variable name as assigned by the user and the values held.So how do I do that
I don't. Confused? OK, let me explain, when I started off, I might have thought in this fashion, but when I spend some time learning Assembly and the way computers see memory and stack, etc. I changed the way I look at things. Let me show you some code that is generally used by a lot of beginners, where they might need a dynamic variable.local ("button " .. i ) = display.newButton()
where the i can be a number that we do not have an idea about at this point in time. Think about it again, isn't this similar to what we call arrays? So how about
local button={} button[i] = display.newButton()
This will offer you the same functionality as what you were after, BUT... there is a small catch, if you are going by the index i, and you remove an item or add an item somewhere in between, the rest of the items in the array get all mixed up. So, how do we fix that? Easy...
local button = {} button["button"..i] = display.newButton()
Now even if you delete a particular button or insert a new button, the index will remain as buttonX and will not get renumbered.
Comments
Post a Comment