Control Flow
Conditions must be Bool (no truthiness: if 1 is an error).
7.1 Conditionals
Conditions must be Bool (no truthiness: if 1 is an error).
x = 7
if x > 5
println("big")
elseif x > 2
println("medium")
else
println("small")
end
label = x > 5 ? "big" : "small" # ternary
x > 5 && println("short-circuit if")
x > 10 || println("short-circuit unless")7.2 Loops
for i in 1:5
println(i)
end
for i in 10:-2:1; print(i, " "); end # 10 8 6 4 2
for (i, v) in enumerate(["a", "b"]); println(i, " => ", v); end
for (k, v) in Dict(:a => 1, :b => 2); println(k, "=", v); end
for (x, y) in zip(1:3, 'a':'c'); println(x, y); end
for i in 1:3, j in 1:2 # nested loop shorthand
println((i, j))
end
n = 0
while n < 3
global n += 1 # `global` needed when modifying a global inside a loop in a script
end
for i in 1:10
i % 2 == 0 && continue
i > 7 && break
print(i, " ")
end7.3 Compound expressions & blocks
z = begin
a = 1
b = 2
a + b
end # 3
z = (a = 1; b = 2; a + b)7.4 Scope rules
Functions, loops, let, comprehensions introduce local scope.
At top level (global scope) inside a script, assigning to a global from a loop requires global (the REPL is more lenient — "soft scope").
let creates a fresh binding:
Closures capture variables by reference.
let x = 1, y = 2
x + y
end