Calculation Expression Parser with Nesting and Variables in ActionScript
Posted
by yuletide
on Stack Overflow
See other posts from Stack Overflow
or by yuletide
Published on 2010-03-12T21:45:34Z
Indexed on
2010/03/12
21:47 UTC
Read the original article
Hit count: 460
Hi There, I'm trying to enable dynamic fields in the configuration file for my mapping app, but I can't figure out how to parse the "equation" passed in by the user, at least not without writing a whole parser from scratch! I'm sure there is some easier way to do this, and so I'm asking for ideas!
Basic idea:
public var testString:String = "(#TOTPOP_CY#-#HISPOP_CY#)/#TOTPOP_CY#";
public var valueObject:Object = {TOTPOP_CY:1000, HISPOP_CY:100};
public function calcParse(eq:String):String {
// do calculations
return calculatedValue
}
So far, I was thinking of splitting the expression by either the operators, or maybe the variable tokens, but that gets rid of the parenthetical nesting. Alternatively, use a series of regex to search and replace each piece of the expression with its value, recursively running until only a number is left. But I don't think regex does math (i.e. replace "\d + \d" with the sum of the two numbers) Ideally, I'd just do a find/replace all variable names with their values, then run an eval(), but there's no eval in AS...
eesh
I downloaded some course materials for a course on compiler design, so maybe I'll just write a full-fledged calculator language and parser and port it over from the OTHER flex (the parser generator) :-D
© Stack Overflow or respective owner