Conditions & loops

Conditions

See official documentation.

In Typst, you can use if-else statements. This is especially useful inside function bodies to vary behavior depending on arguments types or many other things.

#if 1 < 2 [
  This is shown
] else [
  This is not.
]
Rendered image

Of course, else is unnecessary:

#let a = 3

#if a < 4 {
  a = 5
}

#a
Rendered image

You can also use else if statement (known as elif in Python):

#let a = 5

#if a < 4 {
  a = 5
} else if a < 6 {
  a = -3
}

#a
Rendered image

Booleans

if, else if, else accept only boolean values as a switch. You can combine booleans as described in types section:

#let a = 5

#if (a > 1 and a <= 4) or a == 5 [
    `a` matches the condition
]
Rendered image

Loops

See official documentation.

There are two kinds of loops: while and for. While repeats body while the condition is met:

#let a = 3

#while a < 100 {
    a *= 2
    str(a)
    " "
}
Rendered image

for iterates over all elements of sequence. The sequence may be an array, string or dictionary (for iterates over its key-value pairs).

#for c in "ABC" [
  #c is a letter.
]
Rendered image

To iterate to all numbers from a to b, use range(a, b+1):

#let s = 0

#for i in range(3, 6) {
    s += i
    [Number #i is added to sum. Now sum is #s.]
}
Rendered image

Because range is end-exclusive this is equal to

#let s = 0

#for i in (3, 4, 5) {
    s += i
    [Number #i is added to sum. Now sum is #s.]
}
Rendered image
#let people = (Alice: 3, Bob: 5)

#for (name, value) in people [
    #name has #value apples.
]
Rendered image

Break and continue

Inside loops can be used break and continue commands. break breaks loop, jumping outside. continue jumps to next loop iteration.

See the difference on these examples:

#for letter in "abc nope" {
  if letter == " " {
    // stop when there is space
    break
  }

  letter
}
Rendered image
#for letter in "abc nope" {
  if letter == " " {
    // skip the space
    continue
  }

  letter
}
Rendered image