Onur Yıldırım
Onur Yıldırım

Reputation: 33702

AS3 arguments

Why do you think the code below does not work? What would you change/add to make it work?

Any help is appreciated..

function TraceIt(message:String, num:int)
{
    trace(message, num);
}

function aa(f:Function, ...args):void
{
    bb(f, args);
}

aa(TraceIt, "test", 1);

var func:Function = null;
var argum:Array = null;

function bb(f:Function, ...args):void
{
    func = f;
    argum = args;
    exec();
}

function exec()
{
    func.apply(null, argum);
}

I get an ArgumentError (Error #1063):

Argument count mismatch on test_fla::MainTimeline/TraceIt(). Expected 2, got 1.

..so, the passed parameter (argum) fails to provide all passed arguments..

..Please keep the function structure (traffic) intact.. I need a solution using the same functions in the same order.. I have to pass the args to a variable and use them in the exec() method above..

regards

Upvotes: 2

Views: 7679

Answers (3)

Onur Yıldırım
Onur Yıldırım

Reputation: 33702

Ok, here is the solution.. after breaking my head : )

    function TraceIt(message:String, num:int)
    {
        trace(message, num);
    }

    function aa(f:Function=null, ...args):void
    {
        var newArgs:Array = args as Array;
        newArgs.unshift(f);
        bb.apply(null, newArgs);
    }

    aa(TraceIt, "test", 1);

    var func:Function = null;
    var argum:*;

    function bb(f:Function=null, ...args):void
    {
        func = f;
        argum = args as Array;
        exec();
    }

    function exec():void
    {
        if (func == null) { return; }
        func.apply(this, argum);
    }

This way, you can pass arguments as variables to a different function and execute them..

Thanks to everyone taking the time to help...

Upvotes: 7

Kekoa
Kekoa

Reputation: 28250

Change your bb function to look like this:

function bb(f:Function, args:Array):void
{
    func = f;
    argum = args;
    exec();
}

As you have it now, it accepts a variable number of arguments, but you are passing in an array(of the arguments) from aa.

Upvotes: 1

Lobstrosity
Lobstrosity

Reputation: 3936

When TraceIt() eventually gets called, it's being called with 1 Array parameter, not a String and int parameters.

You could change TraceIt() to:

function TraceIt(args:Array)
{
     trace(args[0], args[1]);
}

Or you could change exec() to:

function exec()
{
     func.apply(null, argum[0].toString().split(","));
}

...as it appears when you pass "test", 1, you end up with array whose first value is "test,1". This solution doesn't work beyond the trivial case, though.

Upvotes: 1

Related Questions