Page 1 of 1

How to set dynamic variable names?

Posted: 20 Apr 2016 18:09
by akhileshg1988
Hi there!
Please enlighten me as to how to set a variable name containing another variable (whose value keeps on changing)?
What I am trying to do is store all the incoming messages (received between a certain time frame) into different variables and I want to name these variables incrementally as "inc_msg_1" (for the first msg received during the time frame), "inc_msg_2" (for the second msg) and so on.
For achieving this, I want to first create a variable, "i" which shall be assigned the value zero and then I'll increment this variable as "i=i+1". Now for the variables that'll store the incomng msgs, I wish to create a single variable named "inc_msg_i". The problem is that the "i" in "inc_msg_i" does not get treated as an already declared variable and therefore, I am unable to get self-incrementing variable names i.e. inc_msg_1, inc_msg_2, .....
Kindly help.

Re: How to set dynamic variable names?

Posted: 20 Apr 2016 19:52
by Martin
Hi,

I recommend to use either a list or a map to store the messages in:

Code: Select all

if (global_message_list==null)
{
   global_message_list = newList();
}
...
addElement(global_message_list, "a message");
Alternatively you could use a map:

Code: Select all

if (global_message_map==null)
{
   global_message_map = newMap();
}
...
addMapEntry(global_message_map, "inc_msg_"+i, "a message");
Theoretically you could also use the functions setValue/getValue to create and read variables using a dynamic name:

Code: Select all

setValue("inc_msg_"+i, "a message");
message = getValue("inc_msg_"+i, "default value");//default value is returned when the variable does not exist
Please also check the help page of action script and the script examples page.

Regards,
Martin

Re: How to set dynamic variable names?

Posted: 28 Apr 2016 04:28
by akhileshg1988
Hey Martin
As regards the part of your message where you stated "Theoretically you could also use the functions setValue/getValue to create and read variables using a dynamic name:

setValue("inc_msg_"+i, "a message");
message = getValue("inc_msg_"+i, "default value");//default value is returned when the variable does not exist",

I am most interested in knowing as to how can I set dynamically the name of the variable "message" highlighted in red. More specifically, I want to create incrementing variables i.e. message_1, message_2, message_3 and so on in place of the highlighted variable"messgae".

Kindly guide.

Re: How to set dynamic variable names?

Posted: 28 Apr 2016 04:56
by bogdyro
Hi. You could use this
for (i in [0 to 10]){
setValue('message_'+i, 'value'+i)}