\HeaderA{reg.finalizer}{Finalization of Objects}{reg.finalizer}
\keyword{programming}{reg.finalizer}
\keyword{environment}{reg.finalizer}
\begin{Description}\relax
Registers an \R{} function to be called upon garbage collection of
object or (optionally) at the end of an \R{} session.
\end{Description}
\begin{Usage}
\begin{verbatim}
  reg.finalizer(e, f, onexit = FALSE)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{e}] Object to finalize. Must be environment or external pointer.
\item[\code{f}] Function to call on finalization. Must accept a single argument,
which will be the object to finalize.
\item[\code{onexit}] logical: should the finalizer be run if the object is
still uncollected at the end of the \R{} session?
\end{ldescription}
\end{Arguments}
\begin{Value}
\code{NULL}.
\end{Value}
\begin{Note}\relax
The purpose of this function is mainly to allow objects that refer to
external items (a temporary file, say) to perform cleanup actions when
they are no longer referenced from within \R.  This only makes sense
for objects that are never copied on assignment, hence the restriction
to environments and external pointers.
\end{Note}
\begin{SeeAlso}\relax
\code{\LinkA{gc}{gc}} and \code{\LinkA{Memory}{Memory}} for garbage collection and
memory management.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
f <- function(e) print("cleaning....")
g <- function(x){ e <- environment(); reg.finalizer(e,f) }
g()
invisible(gc()) # trigger cleanup
\end{ExampleCode}
\end{Examples}

