The language / Conditions and loops
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
02 The language / 05
Conditions and loops
Comparing, combining, choosing and repeating: always with true or false, never anything vaguer.
A program decides what to do by asking questions whose answer is true or false. This page starts with asking them (comparisons) and combining them (and, or, not), then moves on to acting on the answer: running code only when something holds, choosing between two values, and repeating while a condition stays true. Since a condition is only ever a Boolean, a reader never has to work out what a number or nil would count as.
Comparisons
The comparison operators, ==, !=, <, <=, > and >=, give true or false. That answer is a value like any other, so you can keep it in a variable:
print(1 < 2) # prints true
print(1 + 2 == 3) # prints true
const total = 150
const is_big = total > 100
print(is_big) # prints trueIn 1 + 2 == 3, the arithmetic happens first (see operators).
Equal or not
== and != need two values that could be equal: two of the same type, an Int and a Float, or a T? with a T or nil. Anything else would always give the same answer, so it is an error:
print(0 == false) # error: can't compare an Int with a Boolean; they're never equalWhen the comparison is allowed, this is how equality works:
- Ints and Floats compare by numeric value, exactly:
1 == 1.0istrue. - Strings are equal when their text is identical:
"a" == "A"isfalse. - NaN (from Float overflow) is not equal to anything, not even itself.
Comparing with nil is how you check a value that might be missing; checking for nil shows what such a check lets you do afterwards.
Greater or less
<, <=, > and >= only work on numbers. nil < 1, true > false and "a" < "b" are errors.
Comparisons can't be chained: compare two values at a time. For a range, join two comparisons with and, as in 1 < x and x < 3:
print(1 < x < 3) # error: comparisons can't be chained; compare two values at a timeLogic: and, or, not
Logic is written in words. and, or and not work on true and false only, and give true or false. With and, both sides must be true; with or, either may be; not turns one around:
const x = 5
const done = false
print(x > 0 and x < 10) # prints true
print(x < 0 or x > 10) # prints false
print(not done) # prints trueAny other value is an error, as in 1 and true or not nil. As for grouping, not binds tightest, and and binds tighter than or, so a or b and c is a or (b and c).
The right side only runs when it decides the result. In a and b, b is skipped when a is false; in a or b, b is skipped when a is true. Use this to guard a risky step behind a safe one: in if d != 0 and 10 / d > 1, the division only happens when d isn't zero.
A not directly before a comparison could mean two things, so it is an error. Use parentheses to say which:
const done = false
const count = 3
print(not done == true) # error: ambiguous 'not' before a comparison; write 'not (a == b)' to negate the comparison, or '(not a) == b'
print(not (count == 0)) # prints true
print(count != 0) # prints trueNot this
not (count == 0)
Write this
count != 0, which says the same and reads better
Conditions: if, else if, else
An if runs a block of code only when its condition is true. Add else if branches to test more conditions in turn, and an else for when none of them hold. The first branch whose condition is true runs, and the others are skipped:
const temperature = 25
if temperature > 30
print("hot")
else if temperature > 20
print("warm") # prints warm
else
print("cold")
endelse if and else are optional, and else comes last. if, each else if, else and end start their own lines, and the condition is alone on its line too. A block if never uses then and never fits on one line.
True or false, nothing else
The condition must be true or false. Anything else is an error, even nil and 0. That holds for the one-line if and for the block alike:
const count = 3
print(if count then 1 else 2) # error: condition must be true or false, got Int
if count > 0
print("some") # prints some
endNot this
if count or if user
Write this
if count > 0, or if user != nil for a value that might be nil
else if or a nested if
else if must be on one line. It continues the chain and shares the chain's single end. An else with an if on the next line is something else: a separate if, nested inside the else, which needs its own end:
const n = 4
if n > 10
print("big")
else
if n > 3 # a nested if, not part of the chain
print("medium") # prints medium
end
print("not big") # prints not big
endA block if is a statement, not a value: it does something, and gives nothing back. To pick a value, use the one-line form below.
Choosing a value: if ... then ... else
When you need one of two values, write the choice on one line. if score > 50 then 2 else 1 reads as "if score > 50, then 2, else 1":
const score = 70
const done = true
const grade = if score > 50 then 2 else 1
print(grade) # prints 2
print(if done then 1 else 0) # prints 1As with every condition, it must be true or false. Only the chosen side runs, so if d != 0 then 10 / d else 0 never divides by zero. To choose by an enum's value, use a when instead; see when as a value.
The one-line form is kept small:
- It must fit on one line. For anything longer, use an
ifblock. elseis required, since there must always be a value.- It can't contain another one. Use an
ifblock withelse ifinstead:
const a = false
const b = true
const x = if a then 1 else if b then 2 else 3 # error: an inline 'if' can't contain another inline 'if'; use an 'if' block with 'else if'It must be a whole value: the right side of =, an argument in f(...), or inside parentheses. As part of a larger expression, wrap it in parentheses:
const a = true
const x = 1 + if a then 2 else 3 # error: an inline 'if' must be a whole value; wrap it in parentheses: 1 + (if a then b else c)
const y = 1 + (if a then 2 else 3)
print(y) # prints 3On its own line, to do one thing or another, it is an error. That's what the if block is for:
const ok = true
if ok then print(1) else print(2) # error: 'if ... then ... else' on one line is only for values, as in 'x = if a then b else c'; here, use an 'if' blockSometimes the choice takes more than one line, and you want its result after the if. Variables declared inside a branch exist only in that branch (see scope), so declare the variable before the if and set it in each branch:
const score = 70
var grade = 0
if score > 50
grade = 2
else
grade = 1
end
print(grade) # prints 2Loops: while
A while loop repeats its body as long as its condition is true. Like every condition, it must be true or false. The condition is checked before each pass, so here i counts up to 3 and the loop stops:
var i = 1
while i <= 3
print(i)
i = i + 1
end
# prints 1
# prints 2
# prints 3break and continue
Inside the body, break leaves the loop at once, and continue skips the rest of this pass and goes on to the next:
var n = 0
while n < 10
n = n + 1
if n % 2 == 0
continue
end
if n > 5
break
end
print(n)
end
# prints 1
# prints 3
# prints 5breakandcontinuebelong to the innermostwhileloop oreachblock. Anywhere else they are an error, and they can't leave a method.- Code right after
breakorcontinuecan never run, so it is an error.
There is no until or for. Use while, or each on a collection (see looping over an array).