Get var value from string containing var name?
by Gavin Doherty · in Torque Game Engine · 03/16/2006 (12:02 pm) · 3 replies
Say I have a variable:
$foo = 5;
And then I have a string containing that variable's name:
%bar = "$foo";
is there any way I can get the value of $foo from the string %bar?
e.g. I would like to do something like this:
echo(eval(%bar));
which would echo 5 to the console. But in reality this gives me "Syntax Error in Input". So it seems 'eval' only works with functions. Is there any equivalent function that will work for strings as described?
Also, is there a function that could handle the following:
new ScriptObject(myScriptObject){
myVar = 5;
}
%str = "myScriptObject.myVar";
echo(eval(%str));
Thanks.
$foo = 5;
And then I have a string containing that variable's name:
%bar = "$foo";
is there any way I can get the value of $foo from the string %bar?
e.g. I would like to do something like this:
echo(eval(%bar));
which would echo 5 to the console. But in reality this gives me "Syntax Error in Input". So it seems 'eval' only works with functions. Is there any equivalent function that will work for strings as described?
Also, is there a function that could handle the following:
new ScriptObject(myScriptObject){
myVar = 5;
}
%str = "myScriptObject.myVar";
echo(eval(%str));
Thanks.
Torque 3D Owner Rubes
Thus, your statement echo(eval(%bar)); does the following:
1. eval(%bar)
2. then echo the results of that.
eval(%bar) basically would create the string "$foo" and excecute that as a statement. But it's not a statement, so you get a syntax error.
What you would want to do is something like this:
eval("echo(" @ %bar @ ");");
That would create the string "echo($foo);" (remember the last semicolon too) and then execute it, which would echo the value of $foo to the console, which is 5.
You would have to modify that to accomplish what you want, of course.