Reputation: 80505
How can I eval Math formulas with AS3?
Nothing fancy, things like (10/3)*4+10
.
Thanks.
Upvotes: 4
Views: 2743
Reputation: 2702
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]);
}
}
}
Upvotes: 9
Reputation: 961
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.
Upvotes: 1