Control Flow
Conditionals, loops, and flow control statements in Soli.
If/Else Statements
if / else / elsif
Conditional branching statements.
let age = 18
# Simple if
if (age >= 18)
print("Adult")
end
# If-else
let score = 75
if (score >= 60)
print("Pass")
else
print("Fail")
end
# Else-if chain
let grade = 85
let letter
if (grade >= 90)
letter = "A"
elsif (grade >= 80)
letter = "B"
elsif (grade >= 70)
letter = "C"
elsif (grade >= 60)
letter = "D"
else
letter = "F"
end
print(letter); # "B"
The then Keyword
then
The then keyword is an optional separator between the condition and the body of an if or elsif statement.
It improves readability, especially for single-line conditionals.
# Multi-line with then
if age >= 18 then
print("Adult")
end
# Single-line with then
if user != null then print("Welcome, " + user.name) end
# Works with elsif too
let x = 42
if x > 100 then
print("big")
elsif x > 10 then
print("medium")
else
print("small")
end
# Parentheses and then can be combined
if (score >= 90) then
grade = "A"
end
# Without then (also valid)
if age >= 18
print("Adult")
end
Note: then is purely syntactic sugar. Both if condition then ... end and if condition ... end are equivalent.
Parentheses around the condition are also optional.
While Loops
while
Repeats while a condition is true.
let i = 0
while (i < 5)
print("Count: " + str(i))
i = i + 1
end
# Output: Count: 0, 1, 2, 3, 4
For Loops
for ... in
Iterates over collections or ranges.
# Iterate over array
let fruits = ["apple", "banana", "cherry"]
for (fruit in fruits)
print(fruit)
end
# Iterate with range
for (i in range(0, 5))
print(i); # 0, 1, 2, 3, 4
end
# Range with step
for (i in range(0, 10, 2))
print(i); # 0, 2, 4, 6, 8
end
# Nested loops
for (i in range(1, 4))
for (j in range(1, 4))
print(str(i) + " x " + str(j) + " = " + str(i * j))
end
end
Postfix Conditionals
if / unless
Ruby-style postfix conditionals for concise one-liners.
let x = 10
print("big") if (x > 5)
let y = 3
print("small") unless (y > 5)
let status = "active"
print("Welcome!") if (status == "active")
print("Account locked") unless (status != "banned")
Ternary Operator
condition ? true_value : false_value
Inline conditional expression.
let x = 10
let size = x > 5 ? "large" : "small"
print(size); # "large"
# Nested ternary
let grade = 85
let letter = grade >= 90 ? "A"
: grade >= 80 ? "B"
: grade >= 70 ? "C"
: grade >= 60 ? "D"
: "F"
print(letter); # "B"
Break and Continue
break
Exits the current loop immediately.
continue
Skips to the next iteration of the loop.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = 0
for (n in numbers)
if (n % 2 == 0)
continue; # Skip even numbers
end
if (n > 7)
break; # Stop at first number > 7
end
sum = sum + n
end
print("Sum of odd numbers < 7: " + str(sum)); # 1+3+5+7 = 16