Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eval math formula string with ActionScript

How can I eval Math formulas with AS3? Nothing fancy, things like (10/3)*4+10.

Thanks.

like image 602
Francisc Avatar asked Dec 09 '22 22:12

Francisc


1 Answers

While you could use a huge eval lib like D.eval or AS3Eval, all you really need is something like this simple MathParser (More info about the MathParser)

Here's how you'd use the MathParser:

package {
    import bkde.as3.parsers.*;
    import flash.display.Sprite;
    public class MathTest extends Sprite {
        public function MathTest() {
            var parser:MathParser = new MathParser([]);
            var compiledObj:CompiledObject = parser.doCompile("(10/3)*4+10");
            var answer:Number = parser.doEval(compiledObj.PolishArray, []);

            // EDIT: In case you wanted variables
            var xyParser:MathParser = new MathParser(["x", "y"]);
            var xyCompiledObj:CompiledObject = xyParser.doCompile("(x/3)*y+10");
            var xyAnswer:Number = xyParser.doEval(xyCompiledObj.PolishArray, [10, 4]);
        }

    }

}
like image 60
Patrick Avatar answered Jan 15 '23 18:01

Patrick