PDA

View Full Version : Calling a Function with variable values


Daisukereds
12-29-2008, 05:00 PM
Hi people!

I found this code I'm trying to understand (and I'm a newbie in Flash), therefore I need help =P.

Anyway, there are several functions with the same name with a number at the end, called like this => "sortType1", "sortType2", ...
How can you call them using a variable's value (the value is randomly assigned) ??

In any case you want to know what the code looks like, it calls them like this (but gives an error "expecting identifier before this") :

var _loc_3:String;
_loc_3.this["sortType" + _id]();

Thanks in advance!

Eric Schleeper
12-31-2008, 12:24 AM
you're trying to concatenate to create the function's name, and although it is good thinking, it doesn't work like this.
Also, I don't know why you have "this" in there.
Also, _loc_3 is just a plain old String, and sortType1() is not a method of a string.
I need to see some more of your code for it to make sense, or have a better idea of what you are trying to do.
I think if you understood a little bit more about OOP and how you pass parameters to a function then things would make more sense.

Bunney lord
12-31-2008, 03:18 PM
This is how I would call a random function using a variable, I don't quite get what your trying to do with that code, but to call functions with variables, you use the [] syntax.

function test1():String {//The first test function
return("test1");
}
function test2():String {//The second test function
return("test2");
}
function test3():String {//The last test function
return("test3");
}
var randNum:Number = Math.round(Math.random()*2+1);//Makes a variable randomly set to 1, 2, or 3
trace(["test"+randNum]());//Calls a function using the variable and the [] syntax, and traces what that function returns.

Daisukereds
12-31-2008, 05:35 PM
So I only have to call the function as in

["sortType" + _id]();
And that would work?

If not, I'll gladly add more code, but it's weird. The .swf works fine, but I used a decompiler and the code throws some errors!, so I'm trying to figure out what's going on and trying to fix it...

Thanks a million

Bunney lord
01-01-2009, 04:34 PM
Ya, that should work.