views:

148

answers:

1

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

A: 

First things first, this isn't really a regex problem.

Next, if you want to use a compiler generator in as3, don't use flex. Use ANTLR, it can target AS3 for output (no need to port it from C). (http://www.antlr.org)

Finally, check out the algorithms for infix to postfix conversion. Here's the wikipedia article on it. (http://en.wikipedia.org/wiki/Shunting-yard_algorithm) It's not too tough to implement.

ablerman
Yeah, I think shunting yard may be the solution... ANTLR looks to be a bit overkill for my needs
yuletide
Built it and it worked like a dream, thanks!
yuletide