Game Development Community

Storing function names in variables

by Mike Stoddart · in Torque Game Engine · 07/12/2002 (9:07 am) · 6 replies

Is there a way to store a function name in a variable, and then call that function somehow from the variable? Here's an example if that question was as clear as mud:

function someFunction()
{
   %functionName = "callme";
   %functioname(1);    // This doesn't work, but it shows what I want to do.
}

function callme(%value)
{
   echo("call me" @ %value);
}

I know this seems like a strange thing to do.

Thanks

#1
07/12/2002 (10:02 am)
Actually, it isn't that strange in Torque script. Try this:

function callMe(%val)
{
    // do something useful
    return %val+1; // or whatever...
}

Then later:

%result = eval("callMe(" @ %arg @ ");");
(edited to better reflect your example needs)
#2
07/12/2002 (10:03 am)
Thanks Tim. Is there any way to pass in a parameter though?

Thanks again.
#3
07/12/2002 (10:07 am)
Hehe. I was altering the example for that while you were asking...

eval() simply evaluates whatever string you pass, so you just need to build the string appropriately. Just don't confuse what should be inside the quotes with what is outside (the semicolons and parens always screw me up cause I forget to include the one in the string etc). Looks butt-ugly, but works great.
#4
07/12/2002 (10:10 am)
Haha, I was just modifying my code to try the very same thing. And it works!

%functionName = "callme(" @ %this @ ");";
   %result = eval(%functionName);

Thanks again.
#5
07/12/2002 (10:12 am)
Glad to be of some help around here. I miss the days when I spent most of my workday doing Tribes script - was such a bad boy...
#6
07/12/2002 (10:14 am)
Yeah I'm doing that at the moment because I can, as I know in the near future I'll be able to spend less time on it.

Anyway, thanks for the great little tip about the eval function.