views:

880

answers:

3

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

+1  A: 

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.

Lobstrosity
thanks but this is a very simple version of the actual code. I mean the TraceIt represents any function passed... meaning it differs all the time..
radgar
+1  A: 

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.

Kekoa
Already tried that in the begining.. Thanks anyway... My solution is below..
radgar
Well it works with the code you posted.
Kekoa
Not even one upvote? Welcome to stack overflow.
Kekoa
I'm a new member, I'm not allowed to vote before 15 reps..
radgar
A: 

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...

radgar