// Basic for loopfor (i = 0; i < 10; i = i + 1) { print(i)}// Multiple variablesfor (i = 0, j = 10; i < j; i = i + 1, j = j - 1) { print(i + ", " + j)}// Can omit partsi = 0for (; i < 5; ) { print(i) i = i + 1}
For-In Loop
The most idiomatic way to iterate in Soul:
Iterating Lists
fruits = ["apple", "banana", "orange"]// Simple iterationfor (fruit in fruits) { print(fruit)}// With index using rangefor (i in 0..fruits.length()-1) { print(i + ": " + fruits[i])}
Iterating Maps
person = { "name": "Alice", "age": 30, "city": "New York"}// Iterate keys onlyfor (key in person) { print(key + ": " + person[key])}// Iterate key-value pairsfor (key, value in person) { print(key + " = " + value)}
Range Iteration
// Inclusive range (0 to 4)for (i in 0..4) { print(i) // 0, 1, 2, 3, 4}// Can use variablesstart = 5end = 10for (n in start..end) { print(n)}
Loop Control
Break
Exit a loop early:
for (i in 0..100) { if (i * i > 50) { break // Exit the loop } print(i)}// Breaking nested loopsfor (i in 0..3) { for (j in 0..3) { if (i == j) break // Only breaks inner loop print(i + "," + j) }}
Continue
Skip to the next iteration:
// Print only even numbersfor (i in 0..10) { if (i % 2 == 1) { continue // Skip odd numbers } print(i)}// Process valid items onlyitems = [1, null, 3, null, 5]for (item in items) { if (item == null) continue print("Processing: " + item)}
Error Handling
Try / Catch
Handle errors gracefully:
try { // Risky operation result = riskyFunction() print("Success: " + result)} catch (error) { print("Error occurred: " + error)}// Can throw custom errorssoul divide(a, b) { if (b == 0) { throw("Division by zero!") } return a / b}try { result = divide(10, 0)} catch (e) { print("Caught: " + e) // "Caught: Division by zero!"}
soul validateUser(user) { if (!user) return false if (!user.email) return false if (!user.age || user.age < 18) return false return true}
Guard Clauses
soul processOrder(order) { // Guard clauses first if (!order) { print("No order provided") return } if (order.items.length() == 0) { print("Order has no items") return } // Main logic here processItems(order.items)}
Loop with Index and Value
items = ["first", "second", "third"]// Manual index trackingi = 0for (item in items) { print(i + ": " + item) i = i + 1}// Or use rangefor (i in 0..items.length()-1) { print(i + ": " + items[i])}