feat: Implement conditional statements

This commit is contained in:
Alvin
2025-09-10 12:54:36 +02:00
parent ea9eead3ba
commit 936fa22257
3 changed files with 63 additions and 2 deletions

View File

@@ -56,4 +56,17 @@ Chimpanzini result x + y
Matteeeo result // prints 15 Matteeeo result // prints 15
``` ```
## Ciao! ### `Tung Tung Tung <operand1> <operator> <operand2>`
This command executes a block of code if a condition is true. The supported operators are `==`, `!=`, `>`, `<`, `>=`, `<=`.
Example:
```tralalero
Biscottini x 10
Tung Tung Tung x > 5
{
Matteeeo "x is greater than 5"
}
```
## Ciao!

7
conditional.tralla Normal file
View File

@@ -0,0 +1,7 @@
Tralalero Tralala
Biscottini x 10
Tung Tung Tung x > 5
{
Matteeeo "x is greater than 5"
}
Bombardiro Crocodilo

View File

@@ -108,7 +108,48 @@ fn parse_and_execute(pc: usize, lines: &Vec<&str>, variables: &mut HashMap<Strin
} }
} }
return pc + 1; return pc + 1;
} else if keyword == "Tung" {
if let (Some(word2), Some(word3), Some(op1_str), Some(op), Some(op2_str)) = (words.next(), words.next(), words.next(), words.next(), words.next()) {
if word2 == "Tung" && word3 == "Tung" {
if let (Some(op1), Some(op2)) = (get_value(op1_str, variables), get_value(op2_str, variables)) {
let condition = match op {
"==" => op1 == op2,
"!=" => op1 != op2,
">" => op1 > op2,
"<" => op1 < op2,
">=" => op1 >= op2,
"<=" => op1 <= op2,
_ => false,
};
let block_start = pc + 2;
let mut block_end = block_start;
let mut brace_count = 1;
for i in block_start..lines.len() {
if lines[i].trim() == "{" {
brace_count += 1;
}
if lines[i].trim() == "}" {
brace_count -= 1;
if brace_count == 0 {
block_end = i;
break;
}
}
}
if condition {
let mut inner_pc = block_start;
while inner_pc < block_end {
inner_pc = parse_and_execute(inner_pc, lines, variables);
}
}
return block_end + 1;
}
}
}
} }
} }
pc + 1 pc + 1
} }