From the documentation ?reg.finalizer
in R:
Inter alia, it provides a way to program code to be run at the end of an R session without manipulating
.Last
. For use in a package, it is often a good idea to set a finalizer on an object in the namespace: then it will be called at the end of the session, or soon after the namespace is unloaded if that is done during the session.
It seems that I can use reg.finalizer()
to run certain code when an R session is ended, but it does not work for me. I have prepared a minimal package at https://github.com/yihui/finalizer-test, which basically contains the code below:
e = new.env()
reg.finalizer(e, function(e) {
message('Bye!')
}, onexit = TRUE)
If I simply run the above code in an interactive R session and quit the session, I can see the message Bye!
, but if I install the above package (you can use devtools::install_github('yihui/finalizer-test')
), load it in an R session, and quit the R session, I don't see the message. I wonder why the finalizer is not executed in this case.
FWIW, when I install the package, I can see the message Bye!
:
$ R CMD INSTALL .
* installing to library ‘/Users/yihui/R’
* installing *source* package ‘finalizer’ ...
** R
** preparing package for lazy loading
No man pages found in package ‘finalizer’
** help
*** installing help indices
Bye!
** building package indices
** testing if installed package can be loaded
* DONE (finalizer)
I don't see the message, either, when I run the command below:
$ R -e "library(finalizer)"
> library(finalizer)
>
>
$