Question

I'm looking the AS3 equivalent of the following JavaScript code:

var funcName = "foo();"
var fHandler = new Function("a",funcName  + "return a + 1"); 

fHandler // now equals a function like function(a){ foo(); return a + 1 }

Ok, it's a very simplified example

The bigger picture is: I have a server that works with a JavaScript Client. Every response this server gives, is a callback to a JavaScript function, providing as arguments the server's response.

As such, it does not use the combersome strict JSON protocol (with quote around attribute names that do not require such quotes to be valid Object-Literal, and so on few other minor differences that would still be a valid Object-Literal in AS3 ), and the server implements over 100 APIs already.

However, now there's a request to produce an Air client for mobile devices.

If I could just do the following - it would be great. It's valid EMCA script, but does not pass for AS3

public function responseFromServer(String:s){
    s = chopCallbackWrap(s); //strips the 'myCallback(' and ')' parts
    //s is now always a string describing a valid Object-Literals not necessarily JSON
    return new Function("", " return " + s ) ();
}

Another aspect is processing in a generic client algorythms distributed on the fly from the server

What is the way to do it in AS3?

Was it helpful?

Solution

There are two solutions I see:

First is to create the new swf file in the runtime with the script you need and load it into Loader.loadBytes().

I recommend you to check this libraries as3abc, as3swf and as3commons. I don't have experience with them, but they all can create and publish swf in runtime (may be some of them don't support scripting within published swf, so it's a task for experiments).

And the second is to execute your JS via ExternalInterface and use the result in as3.

UPD: one more library AS2 eval analog for AS3 - D.eval.

OTHER TIPS

That is not possible in AS3 (or 2), since there is no script compiler built into the runtime (meaning no dynamic interpretation of AS3 code from within an AS3 program). There is also no eval function (or rather, it doesn't do what the javascript eval does).

You will probably have to make another API for the flash version, or plug in an external javascript engine somehow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top