[Rd] Using closures in libraries

Luke Tierney luke@nokomis.stat.umn.edu
Sat, 15 Sep 2001 21:21:25 -0500

On Sat, Sep 15, 2001 at 08:53:36PM -0500, Saikat DebRoy wrote:
> I was trying to use closures within a library as follows -
> foo <- local({
>     # some code creating local variables
>     function() {
>         # uses the local variables created above
>     })
> It did not work because call to do_libfixup in library replaces all
> the closure environments by the global environment. One way around
> this would be to do the replacement only for closures that have the
> same environment as the package environment. Basically change the
> relevant lines in envir.c (do_libfixup) with -
> 	while (p != R_NilValue) {
> 	    if (TYPEOF(CAR(p)) == CLOSXP && CLOENV(CAR(p)) != lib)
> 		SET_CLOENV(CAR(p), env);
> 	    p = CDR(p);
> 	}
> In case any one wonders, I know I could wrap the function in a list
> and call the function with foo[[1]]() - but it really does not look
> very natural. Closures are often so useful that it is desirable that
> they can be used from libraries.
> Can someone comment whether this change can be made and whether this
> would cause any problems?

Unfortunately it would cause problems.  What is currently done is a
fairly gross hack that is intended to get .Global env into the picture
and to avoid a situation where saving one function from the library in
a workspace drags in the whole library.  It accomplishes that but
throws out the baby with the bath water.  The fix you suggest would
cause these problems to reappear (though in a reduced form).  We need
to redesign the whole mechanism, and I'm mildly optimistic that will
happen before 1.4 is released.

There is an easy workaround though: install the package with --save.
That preserves environments in a sensible way (and is basically what
we need to emulate for the standard case).


Luke Tierney
University of Minnesota                      Phone:           612-625-7843
School of Statistics                         Fax:             612-624-8868
313 Ford Hall, 224 Church St. S.E.           email:      luke@stat.umn.edu
Minneapolis, MN 55455 USA                    WWW:  http://www.stat.umn.edu
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch