6.11 Restore state with base::on.exit()

on.exit records the expression given as its argument as needing to be executed when the current function exits even when exiting due to an error.

It is really useful for functions like options() and par() as they return the old value when you provide a new value.

pi
#> [1] 3.141593

neat <- function(x, sig_digits) {
  op <- options(digits = sig_digits)
  on.exit(options(op), add = TRUE)
  
  print(x)
}

neat(pi, 2)
#> [1] 3.1

pi
#> [1] 3.141593