Joe
Joe

Reputation: 3

Pass unevaluated variable as parameter

How do I use an unevaluated (and/or possibly undefined) variable as a parameter for a function? For example:

function myFun(a:int):void {
    a = 5;
}

If you are familiar with Mathematica it would be equivalent to:

f[a_Integer]:=a=5
Attributes[f]={HoldAll};

The core idea being that it is the variable's name itself which I want to pass to the function, not the value which is current associated with the variable's name.

Upvotes: 0

Views: 209

Answers (2)

J. Holmes
J. Holmes

Reputation: 18546

Another way you could solve the problem is to use closures to change evaluation scopes.

public class A {
    public static function myFun(setter:Function):void {
        setter(5);
    }
}

public class B {
    function someOtherFunction() {
        var val:Number;
        A.myFun(function(v:Number):void { val = v; });
        trace(val); // 5
    }
}

Instead of passing a value, I'm passing a function that is bound in the calling scope that is evaluated in the callee's scope.

Upvotes: 0

Julio Rodrigues
Julio Rodrigues

Reputation: 3413

You can pass a string.

private function my_fun(name:String):void {
    trace(this[name]);
}

Example of use:

public class Main extends Sprite {

public var a:int = 5;
    ....
    public function Main():void {
            my_fun("a");
    }

According to these guys: get string representation of a variable name in as3 if it's a classe you can get it's name. If it's a local variable you cannot, the reason is probably related with efficience (the name gets lost on compiling phase)

Upvotes: 1

Related Questions