- Home /
Variable inside a function's NAME - does it work?
I have 10 functions:
function MyFunction1(){ }
function MyFunction2(){ }
function MyFunction3(){ }
...etc
Is there a way to call a specific function depending on the value of an integer i that takes values from 1 to 10?
Calling MyFunction(i)() after having set a value for i doesn't work.
Answer by musicman3x · Jan 02, 2012 at 07:40 PM
You can create an array of function pointers or delegates and then index into the array when calling the function.
Example in C#:
delegate void Delegate();
Delegate[] MyFunctions = new Delegate[3];
void Init()
{
MyFunction[0] = MyFunction1;
MyFunction[1] = MyFunction2;
MyFunction[2] = MyFunction3;
}
void DoWork(int i)
{
MyFunctions[i]();
}
Hope that helps.
I guess this works in JS too since it's a built-in array. Thanks, I'll try it out.
Answer by Statement · Jan 02, 2012 at 08:31 PM
You could also use SendMessage, but delegates are faster.
SendMessage("MyFunction" + i);
I use this "Send$$anonymous$$essage("$$anonymous$$yFunction" + i);" and it's work thanks very much