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

base::on.exit() overwrites the deferred actions registered in the previous call.

on_exit_last_one_wins <- function() {
  cat("put on socks\n")
  on.exit(cat("take off socks\n"))
  
  cat("put on shoes\n")
  on.exit(cat("take off shoes\n"))
}

on_exit_last_one_wins()
#> put on socks
#> put on shoes
#> take off shoes