Eval math formula string with ActionScript

谁说胖子不能爱 提交于 2019-12-12 11:39:49

问题


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

Thanks.


回答1:


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]);
        }

    }

}



回答2:


I believe D.eval API is what you are looking for.




回答3:


If you'd like to avoid using libraries, you could try using the ExternalInterface.call to get access to Javascript's eval function.

For example:

var formula:String = '1+1';
var result:* = ExternalInterface.call('eval', formula);

You may want to check if result == 'undefined' as that would signify an error in the formula syntax.



来源:https://stackoverflow.com/questions/11460718/eval-math-formula-string-with-actionscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!