11.3. defer and defer_delete macros
The DEFER module implements the defer pattern — the ability to schedule cleanup
code to run at scope exit, similar to Go’s defer. The deferred block is moved
to the finally section of the enclosing scope at compile time.
All functions and symbols are in “defer” module, use require to get access to it.
require daslib/defer
Example:
require daslib/defer
[export]
def main() {
print("start\n")
defer() {
print("cleanup runs last\n")
}
print("middle\n")
}
// output:
// start
// middle
// cleanup runs last
Two placements are compile errors, because the enclosing finally would not run
once per scope exit: directly in a loop body (the loop’s finally runs once, after
the loop), and at the top level of a lambda or generator body (that finally is the
lambda’s finalizer and runs on delete, not per call). Enclose the defer in a
bare { } block to give it a per-iteration or per-call scope; to run code on
delete, write the lambda’s finally explicitly.
11.3.1. Function annotations
- DeferMacro
This macro converts defer() <| block expression into {}, and move block to the finally section of the current block
11.3.2. Call macros
- defer_delete
This macro converts defer_delete() expression into {}, and add delete expression to the finally section of the current block
11.3.3. Defer
- defer(blk: block<():void> )
Defers a block of code until scope exit.
- Arguments:
blk : block<void>
11.3.4. Stub
- nada()
helper function which does nothing and will be optimized out