Control Flow

6.1 if / elif / else

if x > 0:
  echo "positive"
elif x < 0:
  echo "negative"
else:
  echo "zero"

6.2 case (must be exhaustive)

For ordinal types (enums, ints, chars), case must cover all values or have an else.

case ch
of 'a', 'e', 'i', 'o', 'u': echo "vowel"
of 'b'..'d', 'f'..'h': echo "early consonant"
else: echo "other"

case cmd
of "start": start()
of "stop": stop()
else: discard

6.3 when (Compile-Time if)

when defined(windows):
  echo "Windows"
elif defined(linux) or defined(macosx):
  echo "Unix-like"
when sizeof(int) == 8: echo "64-bit"
when not defined(release): echo "debug build"

6.4 Loops

for i in 0..4: echo i            # 0 1 2 3 4
for i in 0..<5: echo i           # 0 to 4
for i in countdown(10, 0, 2): echo i
for i in countup(0, 10, 3): echo i
for i, item in ["a", "b"]: echo i, item    # index + value
for key, val in table: echo key, val
for ch in "hello": echo ch

var n = 0
while n < 10:
  inc n
  if n == 3: continue
  if n == 8: break

6.5 block and Labeled Breaks

block outer:
  for i in 0..9:
    for j in 0..9:
      if i * j == 42:
        echo i, " ", j
        break outer

6.6 defer

proc readConfig() =
  let f = open("config.txt")
  defer: f.close()       # runs when the scope exits (even on exception)
  echo f.readAll()