6.8.1 How to write it
Defer
«instrucciones»
EndDefer6.8.2 How it works
When execution reaches Defer, the body does not run: it is pushed onto a stack. When leaving the block that holds the Defer —through the end, Exit, Return or a propagated error— the noted cleanups run, from the last to the first.
ProgramThe last thing opened is the first one closed
Algorithm Ordenado
Write "abro la puerta";
Defer
Write "cierro la puerta";
EndDefer
Write "enciendo la luz";
Defer
Write "apago la luz";
EndDefer
Write "leo un rato";
EndAlgorithmOutput
abro la puerta enciendo la luz leo un rato apago la luz cierro la puerta
The program finishes normally.
1The first
Deferis reached: "cierro la puerta" goes onto the stack.2The second one is reached: "apago la luz" sits on top.
3When the block ends the top one comes off first, "apago la luz", and then "cierro la puerta".
A stack: first cierro la puerta goes in and apago la luz on top. On leaving, apago la luz runs first and then cierro la puerta.
Only what is reached counts: a Defer in a branch not taken notes nothing. Inside a loop, every round notes its own cleanups and runs them when that round ends:
ProgramCleanups per round
Algorithm Vueltas
For i <- 1 To 3 Do
Defer
Write "fin de la vuelta ", i;
EndDefer
If i = 2 Then
Break;
EndIf
Write "vuelta ", i;
EndFor
EndAlgorithmOutput
vuelta 1 fin de la vuelta 1 fin de la vuelta 2
The program finishes normally.
In short
Defernotes a cleanup for when the block is left.- Cleanups run in the reverse of the order they were reached.
- They run when leaving through the end,
Exit,Returnor a propagated error. - A trap ends the program without running them.