Skip to content
Prev 47102 / 63424 Next

on.exit() & sys.on.exit(): Calling them via eval() does not work as hoped

eval() tends to be able to convince normal functions of where they are
executing, but primitive functions use different methods to get their
evaluation context and aren't as easily fooled. It turns out do.call()
works better on primitive functions, and it will work for "on.exit".
However I wasn't able to get 'sys.on.exit' to work.

add_on_exit <- function(what) {
  do.call("on.exit", list(substitute(what), add=TRUE), envir=parent.frame())
}

bar <- function() {
  on.exit(print("exit 1"))
  eval(quote(on.exit(print("exit 2"), add=TRUE))) #nope
  do.call("on.exit", alist(print("exit 3"), add=TRUE))
  add_on_exit(print("exit 4"))
  cat("sys.on.exit():\n")
  x <- sys.on.exit()
  print(x)
  cat("----- exiting\n")
}
[1] "exit 2"
sys.on.exit():
{
    print("exit 1")
    print("exit 3")
    print("exit 4")
}
----- exiting
[1] "exit 1"
[1] "exit 3"
[1] "exit 4"
On Sat, Nov 2, 2013 at 9:24 PM, Henrik Bengtsson <hb at biostat.ucsf.edu> wrote: