defer
defer runs a call when the block it is in ends, however the block is left: at its closing }, by return, by skip or stop, or by an error. Write the cleanup right where you start what needs it:
fn say(s: str) {
print(s)
}
fn work() {
say("open")
defer say("close")
say("working")
}
work()Output:
open
working
closeSeveral defers
They run the last one first, so what was started last is ended first:
fn say(s: str) {
print(s)
}
fn steps() {
defer say("first defer")
defer say("second defer")
say("the block")
}
steps()Output:
the block
second defer
first deferEvery way out
The call runs on every way out of its block, and only for defers the program has reached:
fn say(s: str) {
print(s)
}
fn find(nums: [int], x: int): int {
defer say("searched for ${x}")
nums.walk(i, n) {
if n == x {
return i
}
}
return -1
}
print(find([4, 5, 6], 5))
[1, 2, 3].walk(n) {
defer say("step ${n} ends")
if n == 2 {
stop
}
}Output:
searched for 5
1
step 1 ends
step 2 endsreturn: the value is worked out first, then the call runs, then the function is left. Infind,iis known before the message is printed.- A block inside a block: a defer in an
ifor a walk runs when that block ends, so a defer in a walk runs at the end of every step. - At the top level of the program: when the program’s code ends. Work started with
spawnmay still be running then; writewait()before the defer’s block ends to wait for it.
Errors
When an error leaves the block, the call runs, and the error goes on as if nothing came in between: a try around it catches it, and an uncaught one is reported at the line that raised it.
fn say(s: str) {
print(s)
}
fn risky() {
defer say("cleaned up")
nums: [int] = [1, 2]
print(nums[5])
}
e: error = nil
try e {
risky()
}
print(e.message)Output:
cleaned up
index 5 out of range (length 2)- An error in the call itself, when the block went well, comes from the call, and goes on from there like any error.
- When both fail, the block’s own error is the one that goes on: it is what went wrong first. The call’s error is dropped.
The variables it sees
The call sees the variables declared before the defer, with the values they have when it runs, not when the defer line was reached:
fn say(s: str) {
print(s)
}
fn count() {
n: int = 1
defer say("n is ${n}")
n = 42
}
count()Output:
n is 42- A variable declared after the
deferis a compile error in its call:y is declared after the defer (at 5:1): a defer sees only the variables declared before it. - A variable the call uses can’t be freed before the block ends;
free(x)is a compile error that names the defer. deferneeds a call: a function (defer f(x)) or a method (defer db.close()). Its result, if it has one, is dropped.
An example
A log that collects lines and writes them in one go. With defer, the last lines are written even when the work fails half way:
obj Log {
lines: [str] = []
fn add(s: str) {
self.lines[] = s
}
fn flush() {
print("writing ${len(self.lines)} lines: ${self.lines.join(", ")}")
self.lines = []
}
}
fn work(log: Log) {
defer log.flush()
log.add("started")
log.add("half way")
throw error(100, "the disk is full")
}
log: Log = Log{}
e: error = nil
try e {
work(log)
}
print("${e.code}: ${e.message}")Output:
writing 2 lines: started, half way
100: the disk is fullLuma has no destructors (code that runs when an object is freed): defer is how cleanup is written. It runs at a place you can see, on every way out, and its errors have somewhere to go.