Game Development Community

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.

#1
03/16/2006 (12:35 pm)
Eval() just creates a string from the parameters it is passed, and then executes that string as if it were a real statement.

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.
#2
03/16/2006 (1:24 pm)
There may be a better way, but:
// set %val to the value of the variable who's name is in the string %bar
eval("%val = " @ %bar @ ";");
#3
03/16/2006 (2:47 pm)
Great. Thanks both of you for your help.