Control flow and functionsSlide 13 of 85
13ifControl flow and functions
if and else
Grammar: if-stmt, block
if-stmtSpecification §2.5
if-stmt = "if" expression block { "else" "if" expression block } [ "else" block ] ;blockSpecification §2.5
block = "{" { statement } "}" ;if, else if and else take a Bool, and only a Bool — an Atom is not a condition, and neither is an Int, a Str or a vector. Braces are always written.
Every pair of braces is a block, and a block may declare names of its own. One that reuses a name from outside hides the outer one until the block ends, even with a different type; the outer variable is untouched and comes back after the closing brace.
if, else if, else
proc main(): void {
frames := 7
if frames > 10 {
echo "a strong colony"
} else if frames > 3 {
echo "coming along"
} else {
echo "needs feeding"
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
A block's own names
proc main(): void {
total := 10
if total > 5 {
total := "ten" // this block's own: hides the outer one
echo total // ten
}
echo total // 10 — untouched
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.