Sunday, May 1, 2011

Eval formula in AS3?

I'm playing around a bit with ActionScript. What I want is that I can display a mathematical function from a string.

E.g. in my working python script I do something like that:

formula = 'x**2 + 3*x'
for x in range( 0, 100 ):
    y = eval( formula )
    graph.display( x, y )

I want to port this to ActionScript, but it seems like there is no more eval since version 3. How can I compute my function values anyway?

From stackoverflow
  • You will have to write an eval yourself. You will have to parse the string and invoke the right operators.

    Here's a link to get you started.

    The Tamarin project has a ECMAScript parser written in ES4. Try this as well.

    "You can even write the entire javascript inside as3, so that you do not need to touch the actual html page." Do you have links / tutorials? – okoman

    Both AS and JS are based on the same ECMAScript standard. So, if you pass a string of AS3 to a container, and use JS's eval on this string, it should work just fine.

    okoman : That's exactly what I want to avoid. ;) Nevertheless seems there is no other solution.
    okoman : Gonna generate some easy-to-parse formula in another languages and send it to flash...
    dirkgently : That is another thought. I did not suggest it since ExternalInterface can quickly become a pain.
  • Something that might also work in your case, is using Javascript eval instead. You can use something like:

    var result = ExternalInterface.call(myEvalFunctionInJS,formula)

    to evaluate math functions.

    This is an somewhat easy and useful workaround as javascript is quite close to actionscript.

    If you put the ExternalInterface call inside an loop, it may become sluggish. To avoid that, you can write the loop in javascript. (You can even write the entire javascript inside as3, so that you do not need to touch the actual html page.)

    edit: Here's an link for that.

    http://www.actionscript.org/resources/articles/745/2/JavaScript-and-VBScript-Injection-in-ActionScript-3/Page2.html

    okoman : "You can even write the entire javascript inside as3, so that you do not need to touch the actual html page." Do you have links / tutorials?
    Mikko Tapionlinna : Sure, here's one: http://www.actionscript.org/resources/articles/745/2/JavaScript-and-VBScript-Injection-in-ActionScript-3/Page2.html
    okoman : oh well, that's pretty easy. Thank you!
  • There is also a seemingly abandoned project to port Tamarin to Flash itself:

    http://eval.hurlant.com/

    Would be awesome if more progress was made, but seems like a curiosity for now.

0 comments:

Post a Comment