public double EvaluateArithExpression(string[] tokens, int start) { tokens = context.ReplaceToValues(tokens, start); string line = Interpreter.GetString(tokens); //Debug.Log("Infix: [" + line + "]"); InfixPrefix IP = new InfixPrefix(ArithOperators); string ipOut = IP.ConvertInfixToPrefix(line); tokens = InfixPrefix.GetTokens(ipOut); //Debug.Log("Prefix: " + ipOut); Stack<double> operands = new Stack<double>(); for (int i = tokens.Length - 1; i > -1; i--) { string token = tokens[i]; if (!ArithOperators.ContainsKey(token)) { double op = 0; if (double.TryParse(token, out op)) operands.Push(op); else context.ThrowError("The operand is not a number. ( " + token + " )"); } else { //its an operator double op1 = operands.Pop(); double op2 = operands.Pop(); operands.Push(ComputeArith(token, op1, op2)); } } return operands.Pop(); }
/// <summary> /// Evaluate a logical expression /// </summary> /// <param name="line"></param> /// <returns></returns> public bool EvaluateLogic(string[] tokens, int start) { tokens = context.ReplaceToValues(tokens, start); string line = Interpreter.GetString(tokens); //Debug.Log("Infix: " + line); InfixPrefix IP = new InfixPrefix(LogicOperators); string ipOut = IP.ConvertInfixToPrefix(line); tokens = InfixPrefix.GetTokens(ipOut); //Debug.Log("Prefix: " + ipOut); Stack<string> operands = new Stack<string>(); for (int i = tokens.Length - 1; i > -1; i--) { string token = tokens[i]; if (!LogicOperators.ContainsKey(token)) { operands.Push(token); } else { //its an operator string op1 = operands.Pop(); string op2 = operands.Pop(); //Debug.Log("OP1 " + op1 + " OP2 " + op2 + " OPR" + token); operands.Push(ProcessCondition(token, op1, op2)); } //Debug.Log("Operands stack [" + Interpreter.GetString(operands.ToArray()) + "]"); } string fin = operands.Pop(); //Debug.Log(fin); return bool.Parse(fin); }