Reputation:
I'm trying to figure out the logic of a game I'm making, the plan is to store a set of functions into an array or vector with each function having a parameter of some kind.
The problem is that when i try to push a function with parameters into the Array, the method gets called because of the (), like this:
arr.push(someFunction(2));
Also if i have this:
var arr:Array = new Array();
arr.push(someFunction(2));
arr[0]();
It obviously won't work because the last line isn't passing any parameters.
Is there an easy way to accomplish this? I guess I could pass an Object or pass an Array as parameter instead, but maybe I'm just missing something.
Upvotes: 0
Views: 726
Reputation: 12264
Pan's answer is the way to go, and I want to add my explanation. In a scripting language like ActionScript, a function call is evaluated immediately. So when you write something like arr.push(someFunction(2));
you aren't pushing the function itself into the array, you're pushing the result of the function. In order to reference the function itself you have to put the function name without the parentheses. In other languages like C, a variable that stores a function is called a delegate.
Can you explain what you're trying to accomplish with this, though? I suspect there's a better way to do it than storing functions in an array.
Upvotes: 0
Reputation: 2101
You may save the function and the parameter, then get them when needed
var functions:Array = [];
functions.push([someFunction, [2]]);//the parameter should be an array
var targetFunction:Function = functions[0][0] as Function;
var targetParameter:Array = functions[0][1] as Array;
targetFunction.apply(null, targetParameter);
Upvotes: 1
Reputation: 1624
you should use closure.
example..
function returnFuncWithArg(arg:Number):Function {
var closureFunc:Function = function():void {
someFunction(arg);
}
return closureFunc;
}
and
var arr:Array = new Array();
arr.push(returnFuncWithArg(2));
arr[0]();
Upvotes: 1