PDA

View Full Version : Accessing a dynamic variable


drmerman
09-23-2006, 01:28 PM
Hey guys. I've come across a problem and I really can't figure it out at all. I was wondering if anybody has any ideas.

The following works :


//a word is entered into a textfield. Temporarily we shall assign it a constant value
string $dynamicWord = "officeBlock";

//after getting the word from the textfield, I want to use it to create a variable, in
//the form = $ <entered word> <attribute> = <value>. In order to create a variable using
//the above string as a name, we first have to create the command in a string.
string $variableCommand = ("string $" + $dynamicWord + "_fish = \"Red\";");

//if we print this we get : string $officeBlock_fish = "Red";

//we then evaluate $variableCommand to create the above variable
eval ($variableCommand);

//the variable, $officeBlock_fish, now exists, and has the value "Red"


The question is, how do I access this variable, bearing in mind it is dynamic?

Say that I want to get the value from $officeBlock_fish, and put it in another variable. I thought I would do the following, but it does not work.

//create a variable containing a short version of the 1st variables name
string $variableShortName = ("$" + $dynamicWord + "_fish");
//this gives us, $officeBlock_fish

//using the eval command, assign $officeBlock_fish to $newVariable
string $newVariable = `eval($variableShortName)`;
I keep on getting syntax errors no matter what I try.

I apologise if this is not explained very well, its been a long day and my brains been running around in circles :scream:

Any help would be really great.

Cheers,
Dr Merman

JackSMillenium
09-23-2006, 08:34 PM
The syntax error comes from the fact that you're evaluating a variable, not an operation. It's as if in the ScriptEditor you typed $officeBlock_fish and hit enter.

A cool trick is to evaluate "assigning the variable to itself", which also happens to return the value of the variable. So what you can do is:

string $newVariable = `eval($variableShortName+"="+$variableShortName)`;

Jack.

drmerman
09-23-2006, 08:34 PM
:thumbsup:

//2nd box SHOULD read

//create a variable containing a short version of the 1st variables name
string $variableShortName = ("$" + $dynamicWord + "_fish");
//this gives us, $officeBlock_fish


//using the evalEcho command, assign $officeBlock_fish to $newVariable
string $newVariable;
evalEcho("string $newVariable = " + $variableShortName);

print $newVariable;
evalEcho combines what is in the brackets into a command, and then evaluates it.

Cheers,
Dr Merman

CGTalk Moderation
09-23-2006, 08:34 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.