6.14 base::on.exit() vs withr::defer()

withr::defer() adds expressions to the top of the stack of deferred actions.

defer_stack <- function() {
  cat("put on socks\n")
  defer(cat("take off socks\n"))
  
  cat("put on shoes\n")
  defer(cat("take off shoes\n"))
}
defer_stack()
#> put on socks
#> put on shoes
#> take off shoes
#> take off socks