Skip to content
Prev 7482 / 12125 Next

[R-pkg-devel] Is there a better way ...?

On Thu, Oct 21, 2021 at 12:15 PM Rolf Turner <r.turner at auckland.ac.nz> wrote:
My suggestion is having a package-specific environment, and Duncan's
is to have a function-specific environment. If you only need this for
this one function, then that should be good enough. If you eventually
want to access the persistent information from multiple functions,
having a package-specific environment would be more useful.

I'm not sure what you are trying to do, but I can't see how you can do
something sensible with a function-specific environment if someone
does

plot.foo(something)
plot.default(1:10)
plot.foo(something else, add = TRUE)

So maybe you would eventually want to set a hook (?setHook) for
plot.new to ensure that no other plot has been created in between,
which could write into this package-specific environment.
Nothing other than the usual reason for not exporting things
unnecessarily, which is to not pollute the user workspace.
Andrew's suggestion looks more complicated than it is. Think of
.fooInfo as a "global" variable, just in your package namespace rather
than .GlobalEnv, so you could do (in your package code)

.fooInfo <- NULL

plot.foo <- function(...)
{
   if (is.null(.fooInfo)) ... # use .fooInfo
   .fooInfo <<- something # set .fooInfo
}

Andrew suggested a separate (and unnamed) environment to store both
.fooInfo and plot.foo, so the setting part becomes a bit more
complicated (but accessing becomes safer in the sense that no other
function can access .fooInfo).

My suggestion is essentially similar, except that you can use <-
instead of <<- because it's an environment.

.fooEnv <- new.env()

plot.foo <- function(...)
{
   if (is.null(.fooEnv$info)) ... # use .fooEnv$info
   .fooEnv$info <- something # set .fooEnv$info
}

Best,
-Deepayan