[Rd] Using closures in libraries

Saikat DebRoy saikat@stat.wisc.edu
15 Sep 2001 20:53:36 -0500


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?
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._