Got you booleans and expressions done?
i.e.
IF (val1+val3*val2) > 8 OR 6<7
{code}
ELSE
{code}
ENDIF
it's surprisingly easy. Just need to convert (1+3*2) > 8 OR 6<7 into reverse polish notation:
1, 3, 2, *, +, 8, >, 6, 7, <, OR
that is using a precedence like this:
lowest
- booleans (AND, OR, NOT)
- comparisons (<, >, =)
- addition + subtraction
- multiplication + division
- exponentials
highest
Once you've got it converted into RPN (ask me on MSN how), it's easy to evaluate. Go through each token in turn.
-If it's a number, push it to the stack.
-If it's an mathematical operator pop two numbers, perform it, and push the result to the stack.
-If it's a comparison, pop two numbers, compare, and push the boolean result to a different stack (I call it the boolstack)
-If it's a boolean op, pop two bools from the boolstack, perform, and push the result.
The resulting value on the boolstack indicates if the expression is true or false.
Using this example:
1, 3, 2, *, +, 8, >, 6, 7, <, OR
1) token in: 1. Treat as number, push.
STACK: 1
BOOLSTACK: {empty}
2) token in: "3". Same:
STACK: 3, 1
BOOLSTACK: {empty}
3) token in: "2".
STACK: 2, 3, 1
BOOLSTACK: {empty}
4) token in: *. Pop two, multiply, and return to stack.
POP 2 & 3, multipled is 6.
STACK: 6, 1
BOOLSTACK: {empty}
5) token in: +. Pop two, add, push.
POP 6 & 1, added is 7.
STACK: 7
BOOLSTACK: {empty}
6) token in: 8. Push:
STACK: 8, 7
BOOLSTACK: {empty}
7) Token in >. Pop top two, see if second val popped is bigger than first (second val popped was the first in)
7 is not > 8, so push "FALSE"
STACK: {empty}
BOOLSTACK: FALSE
8) token: 6
STACK: 6
BOOLSTACK: FALSE
9) token: 7
STACK: 7, 6
BOOLSTACK: FALSE
10) token: <. Pop two, compare, push result to boolstack.
6 is smaller than 7, push "TRUE".
STACK: {empty}
BOOLSTACK: TRUE, FALSE
11) token "OR". Pop two bools, perform operation nad push a bool.
TRUE and FALSE, when put through an OR, returns TRUE. Push TRUE.
Stack: {empty}
BOOLSTACK: TRUE
That's it, we're left with "TRUE" on the boolstack hence the condition wwas true.
Easy. When you get the hang of it