I was surprised just now to find out that `topenv(emptyenv())` equals … `.GlobalEnv`, not `emptyenv()`. From my understanding of the description of `topenv`, it should walk up the chain of enclosing environments (as if by calling `e = parent.env(e)` repeatedly; in fact, that is almost exactly its implementation in envir.c) until it hits a top level. However, `emptyenv()` has no enclosing environments so it should be its own top-level environment (I thought). Unfortunately the documentation on environments is relatively sparse, and the R Internals document doesn’t mention top-level environments.
Concretely, I encountered this in the following code, which signals an error if `env` is the empty environment: while (! some_complex_condition(env) && ! identical(env, toplevel(env))) { env = parent.env(env) } Of course there’s a trivial workaround (add an identity check for `emptyenv()` in the while loop condition) but it got me wondering if there’s a rationale for this result or if it’s “accidental”/arbitrary: the C `topenv` implementation defaults to returning R_GlobalEnv for an empty environment. Is this effect actually useful (and used anywhere)? This is in R 3.4.4 but I can’t find an indication that this behaviour was ever changed. Cheers -- Konrad Rudolph ______________________________________________ R-devel@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel