From 011938cadfd8ed5b0e7b58062179ae5d5337f7a1 Mon Sep 17 00:00:00 2001 From: hut Date: Sun, 14 Apr 2024 19:45:42 +0200 Subject: [PATCH] implement "if" statements with 2 operands + 1 operator --- src/var.rs | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/src/var.rs b/src/var.rs index d30dfb3..7583e48 100644 --- a/src/var.rs +++ b/src/var.rs @@ -4,6 +4,13 @@ use std::env; pub const SCOPE_SEPARATOR: &str = "$"; +pub const TOKEN_EQUALS: &str = "=="; +pub const TOKEN_EQUALS_NOT: &str = "!="; +pub const TOKEN_GREATER_THAN: &str = ">"; +pub const TOKEN_LESS_THAN: &str = "<"; +pub const TOKEN_GREATER_EQUALS: &str = ">="; +pub const TOKEN_LESS_EQUALS: &str = "<="; + pub const DEFAULT_CHAT_SPEED: f32 = 10.0; #[derive(Resource)] @@ -281,7 +288,10 @@ impl GameVars { pub fn evaluate_condition(&self, condition: &str, scope: &str) -> bool { let parts: Vec<&str> = condition.split(" ").collect(); - if parts.len() == 1 { + if parts.len() == 0 { + // Got an empty string, this is always false. + return false; + } else if parts.len() == 1 { // Got something like "if $somevar:". // Check whether the variable evaluates to true. let part = parts[0]; @@ -309,12 +319,67 @@ impl GameVars { .get(Self::normalize_varname(scope, right.as_str()).as_str()) .unwrap_or("".to_string()); } - dbg!(&left); - dbg!(&right); - dbg!(left == right); return left == right; } else { - return false; + // Got something like "if $something != somethingelse bla bla" + let mut left: String = parts[0].to_string(); + if left.contains(SCOPE_SEPARATOR) { + left = self + .get(Self::normalize_varname(scope, left.as_str()).as_str()) + .unwrap_or("".to_string()); + } + + let mut right: String = parts[2..parts.len()].join(" ").to_string(); + if right.contains(SCOPE_SEPARATOR) { + right = self + .get(Self::normalize_varname(scope, right.as_str()).as_str()) + .unwrap_or("".to_string()); + } + let floats = (left.parse::(), right.parse::()); + let operator: &str = parts[1]; + + match operator { + TOKEN_EQUALS => { + if let (Ok(left), Ok(right)) = floats { + return left == right; + } + return left == right; + } + TOKEN_EQUALS_NOT => { + if let (Ok(left), Ok(right)) = floats { + return left != right; + } + return left != right; + } + TOKEN_GREATER_THAN => { + if let (Ok(left), Ok(right)) = floats { + return left > right; + } + return false; + } + TOKEN_GREATER_EQUALS => { + if let (Ok(left), Ok(right)) = floats { + return left >= right; + } + return false; + } + TOKEN_LESS_THAN => { + if let (Ok(left), Ok(right)) = floats { + return left < right; + } + return false; + } + TOKEN_LESS_EQUALS => { + if let (Ok(left), Ok(right)) = floats { + return left <= right; + } + return false; + } + _ => { + error!("Unknown operator '{operator}' in if-condition!"); + return false; + } + } } } }