Created
July 26, 2019 10:40
-
-
Save moodymudskipper/f048f0000e1795694a48696fb10bc312 to your computer and use it in GitHub Desktop.
on.exit for scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To go further:
exit.script <- function() {
eval.parent(.on.exit.exprs)
rm(".on.exit.exprs", envir = parent.frame())
}