Skip to content

Instantly share code, notes, and snippets.

@moodymudskipper
Created July 26, 2019 10:40
Show Gist options
  • Save moodymudskipper/f048f0000e1795694a48696fb10bc312 to your computer and use it in GitHub Desktop.
Save moodymudskipper/f048f0000e1795694a48696fb10bc312 to your computer and use it in GitHub Desktop.
on.exit for scripts
# on.exit for scripts, on.exit2 will create, update or overwrite
# the object .on.exit.exprs (of class expression) in the calling environment
# at the end of the script we evaluate .on.exit.exprs
on.exit2 <- function(expr = NULL, add = FALSE, after = TRUE){
if(!exists(".on.exit.exprs", parent.frame()))
assign(".on.exit.exprs",expression(), envir = parent.frame())
if(add){
if(after)
.on.exit.exprs <<- c(.on.exit.exprs, substitute(expr))
else
.on.exit.exprs <<- c(substitute(expr),.on.exit.exprs)
} else {
.on.exit.exprs <<- as.expression(substitute(expr))
}
}
# then as the last line of the script
eval(.on.exit.exprs)
@moodymudskipper
Copy link
Author

To go further:

exit.script <- function() {
eval.parent(.on.exit.exprs)
rm(".on.exit.exprs", envir = parent.frame())
}

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