0

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.

3 Answers 3

1

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]();
Sign up to request clarification or add additional context in comments.

1 Comment

Problem with this is it adds one copy of that function for every time it is called. That could become a serious memory issue if done often (it is actually recommended by Adobe evangelists and devs that you not use anonymous functions in AS3)
1

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.