4. Control Flow
if / elif / else
let n = 7;
if (n > 10) {
print("big");
} elif (n > 5) {
print("medium");
} else {
print("small");
}
Parentheses around the condition are optional:
if n > 5 {
print("more than five");
}
while
let i = 0;
while (i < 3) {
print("i =", i);
i = i + 1;
}
for — C-style
for (let i = 0; i < 5; i = i + 1) {
print(i); // 0 1 2 3 4
}
for ... in — foreach
Iterate a list, a string (its characters), or a dict (its keys):
for x in [10, 20, 30] {
print(x);
}
for ch in "abc" {
print(ch);
}
for key in { "a": 1, "b": 2 } {
print(key);
}
loop ... in — ranges
a..b goes from a up to (but not including) b:
loop i in 0..5 {
print(i); // 0 1 2 3 4
}
loop { ... } with no range is an infinite loop.
Ternary expression
let x = 8;
let label = x % 2 == 0 ? "even" : "odd";
print(label); // even
A note on break/continue
There is no break/continue keyword yet. Use a boolean flag, or wrap the loop in a function and return:
func firstEven(list) {
for x in list {
if (x % 2 == 0) { return x; } // returns out of the loop
}
return null;
}
print(firstEven([1, 3, 6, 9])); // 6
Next: Functions
Kitteniverse Studios