Control flow
In the terminalela --spec control-flow
if git pull echo "updated"else echo "pull failed"end if if not grep -q needle notes.md echo "no needle"end if for file in $files echo "$file"end for while $running sleep 1end while
foriterates real lists or the lines of command output. Afterin, an expression gives the list:$files,$xs[1:], a call; words do as in a command:*.log,logs/*.log, and a variable or a quoted string with a path or a glob glued to it,$dir/*.logor"$dir"/*.log.rangecounts for a loop that needs numbers:range(5)is[0, 1, 2, 3, 4],range(2, 5)is[2, 3, 4], up to the end and not including it, as a slice$xs[2:5]takes positions, andrange(10, 0, -2)counts down,[10, 8, 6, 4, 2]. A range that never reaches its end,range(5, 2), is[]; a step of 0 or a number that is not whole is an error. It gives an ordinary list, sofor attempt in range(3)runs three times andfor i in range(0, len($xs), 2)takes every other position.whenafter the list keeps the rounds its condition says yes to, and skips the rest:for f in $files when is_big($f); rm $fremoves only the big files. The condition is any conditioniftakes, a command included; a block'swhenends theforline, and its body starts on the next. A one-lineforon the right of an=gives a list (Lists from for).- A loop walks what its list held when it began. A line of the body that changes the list,
xs[$i] = vorxs = list.append($xs, $x), changes it for the lines after the loop, never the rounds:for x in $xswithxs = list.append($xs, $x)in it runs once for each itemxsheld at the start, and the list ends twice as long. - The item is a copy, as every value is (Strict rules): a change to it changes nothing in the list, so a loop that changes items names them by index,
for i, x in $xsandxs[$i]["n"] = 0;ela --lintwarns of a change to the item that nothing after it reads. - A loop's two names, the index or key and the item, differ;
_drops one, and may stand for both:for _, _ in $xs. - A
forloop's own variables, the item and the index, stay set after it with the last round's values, or with the values at abreak. The loop clears them as it starts, so after a loop that ran no rounds they hold nothing, and reading one is an error that names the loop, never a value left from before it. breakleaves the loop it is in, andcontinuegoes on to its next round. A loop named with a label,outer: for ...(the name, a colon, a space, thenfororwhile;a:trueandecho: histay commands), is left or continued from a loop inside it withbreak outerorcontinue outer. Either outside a loop is an error.
outer: for r in $repos for line in $(git -C $r status --short) if str.has_prefix($line, "??") continue outer # untracked files: skip this repository end if end for if $r == "stop" break end if echo "$r is clean"end for
switch #
switch picks the first case whose value equals the one switched on; case with several values matches any of them, and a bare case, last, matches the rest. Only that arm runs, never the next one too.
switch $statecase "none" echo "no run"case "passed", "failed", "stopped" echo "run $run: $state"case echo "run $run is still $state"end switch
- Values compare as
==does, so text and a number never match:case 404against"404"is an error. - No arm matching, and no bare
case, runs nothing. breakandcontinueinside aswitchact on the loop around it.
Values from switch and if #
A switch on the right of an assignment, after return or as an argument gives a value: the
result of the case that matches. Each case holds one expression after its ;, and else; value
comes last. Bash sets the variable in every arm of a case … esac; ela says it once:
# bashcase "$kind" in dir) label=folder ;; link) label=shortcut ;; *) label=other ;;esac
label = switch $kind case "dir"; "folder" case "link"; "shortcut" else; "other"end switch
- A case with lines of work is an error that says to call a proc:
case "dir"; describe_dir($p). - A command in a case runs as anywhere:
case "remote"; $(git remote get-url origin). elseis required, unless the cases name every member of an enum, as Zig's switch must be whole. A member added to the enum is then an error, before line 1, at every suchswitchthat misses it:
enum Mode DEBUG RELEASE PROFILEend enum proc flags(m: Mode) -> string return switch $m case Mode.DEBUG; "-debug" case Mode.RELEASE; "-o:speed" case Mode.PROFILE; "-define:PROFILE=true" end switchend proc
Without its case Mode.PROFILE line it stops before line 1:
build.ela:8:12: error: this switch gives a value and has no else, and its cases miss Mode.PROFILE: add a case for each, or an else
A one-line if gives a value: if cond; a else b, the else required, and else if chains on
the same line. The condition is any condition, a command included. An if over several lines
gives none; a choice among many is a switch that gives a value. Python's a if cond else b
stops before line 1: 'if' after a value: a value chosen by a condition is a one-line if, the condition first: x = if cond; a else b.
# bashif [ "$n" -eq 1 ]; then noun=file; else noun=files; fiif git diff --quiet; then state=clean; else state=changed; fi
noun = if $n == 1; "file" else "files"state = if git diff --quiet; "clean" else "changed"size = if $b > 1_000_000_000; "large" else if $b > 1_000_000; "medium" else "small"
Lists from for #
A one-line for on the right of an assignment gives a list: after its ; comes one expression,
and each round adds its value to the list, in the loop's order. when before the ; keeps only
the items its condition says yes to. Python writes [f for f in files if is_big(f)]; ela writes
the loop it is:
big = for f in $files when file.info($f)["size"] > 1_000_000; $fsizes = for f in $files; file.info($f)["size"]lines = for i, l in $lines; "${i}: $l"pairs = for k, v in $config; "$k=$v"dirty = for d in $repos when not git -C $d diff --quiet; $devens = for i in range(10) when $i % 2 == 0; $i * $i
- It always gives a list, a new one; with nothing kept,
[]. An item that is a variable's list is a copy in it, so a change to one never reaches the other. for i, x in $listandfor k, v in $mapname the index or the key as the ordinaryfordoes, and the loop's names stay set after it in the same way.- The condition after
whenis any conditioniftakes: a comparison, a call that gives a bool,not,and,or, or a command, whose exit code 0 is yes and which runs once for each item. Aforhas onewhen; its conditions join withand. for i in range(n)counts without making range's list, as the ordinary loop does.- Only the one-line form gives a list. A
forover several lines on the right of an=is an error that says to call a proc:sizes = for f in $files; size_of($f). More than one expression after the;is an error too, and so is aforanywhere but the whole value of an assignment. - Python's list comprehension,
[f for f in files], and aforin brackets,[for f in $files; $f], stop before line 1:a list from a loop is a one-line for, with no brackets: xs = for x in $items when cond; $x * 2. - A
forwith nox =on its left is an ordinary loop:for f in $files; $fruns$fas a command, andfor f in $files; str.upper($f)drops what the call gives, an error (Results are kept).
when works in an ordinary for too, one line or several: the body runs only for the items the
condition says yes to.
for f in $files when is_big($f); rm $f for r in $rows when $r["state"] == "open" echo $r["title"]end for
defer #
defer followed by a command or a call runs it when the proc it is in returns, or, at the top level, when the script ends: at its end, by exit, by a failed command, by an error or by a signal no catch signal block covers. The line runs then, with the values its variables have then.
| Form | Runs at the end | Example |
|---|---|---|
defer command | the command | defer kill $server |
defer call(...) | the call | defer file.delete($tmp) |
defer, lines, end defer | the lines, in the order written | the block below |
defer; a; b | the lines after the ;, to the line's end | defer; umount $mnt; rm -rf $tmp |
tmp = $(mktemp)defer file.delete($tmp) server = run ./server --port 8080defer kill $server
defer spin "cleaning up" docker rm -f $id umount $mnt end spin rm -rf $tmpend defer
spininside the block times a slow clean-up and shows it onela --usage's bar;deferitself draws nothing.- Several run last first. A block counts as one, and its lines run in their written order.
- A block is a deferred line of several: a failure or a signal in it ends the block where it came, as it ends a line, and the rules below hold for it whole. Each step that must run whatever the one before did gets a
deferof its own, ortry. return, andbreakorcontinueoutside a loop in the block, are errors, since the block runs after its proc or script has ended; so is adeferinside it.- A
deferthat runs in a loop runs once for each time its line was reached, at the end of the proc or the script, not of the round. - A deferred line that fails is reported as it fails, and the others still run. The script exits with the code it had before, or with the first failed deferred line's when it had none; a proc that would have returned fails as that line did, which
tryon its call catches. - An
exitin a deferred line, in a proc it calls, ends the script, even when the proc it was deferred in failed undertry. - A signal while a deferred line runs stops that line, and the others still run; then the signal goes on as if it had come after them: up from a proc to the
catch signalblock that covers its call, or ending the script. A second one while they run ends ela at once, as a second Ctrl-C always does. execreplaces the process, so nothing deferred runs.- Deferred lines run before the proc or the script waits for the jobs it started (Who waits), so
defer kill $serverends a server first. - At the interactive prompt, a top-level
deferruns when the line typed has finished.