Skip to content

Instantly share code, notes, and snippets.

@greggirwin
Created February 13, 2021 04:33
Show Gist options
  • Save greggirwin/052983865fc684c006b18bbac6c6d2b7 to your computer and use it in GitHub Desktop.
Save greggirwin/052983865fc684c006b18bbac6c6d2b7 to your computer and use it in GitHub Desktop.
Red Defer
; Go lang style defer experiment
deferreds-ctx: context [
stack: []
cur-stack: does [last stack] ; current function's stack
push-frame: does [append/only stack copy []] ; new stack frame
pop-frame: does [take/last stack] ; drop last stack frame
;push-defer: func [blk [block!]] [append/only cur-stack blk] ; LIFO
push-defer: func [blk [block!]] [insert/only cur-stack blk] ; FIFO
do-deferreds: does [foreach blk cur-stack [attempt [do blk]]]
set 'on-exit func [blk [block!]][push-defer blk] ; a.k.a defer; what the user calls to add a deferred call
exiting: does [do-deferreds pop-frame]
entering: does [push-frame]
set 'function-with-deferreds function [spec body][
body: compose/deep [
entering
__def-res: attempt [(body)]
exiting
__def-res
]
function spec body
]
]
outer: function-with-deferreds [][
on-exit [print "leaving outer 1"] ; not done until the function returns
print inner 1
on-exit [print "leaving outer 2"] ; not done until the function returns
print inner 2
on-exit [print "leaving outer 3"] ; not done until the function returns
'outer-result
]
inner: function-with-deferreds [arg [integer!]][
on-exit [print ["leaving inner" arg]] ; not done until the function returns
arg * 10
]
outer
@15926222352
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment