r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
405 stars 56 forks source link

Can't use with/local statements within inner environment in portable class #120

Closed dipterix closed 7 years ago

dipterix commented 7 years ago

The following code will raise exception:

MyClass <- R6::R6Class(
  'MyClass',
  cloneable = FALSE,
  portable = TRUE,
  public = list(
    inner_env = NULL,
    initialize = function(){
      self$inner_env <- new.env(parent = self)
    },
    my_method = function(){
      with(self$inner_env, {
        a <- 1
      })
    }
  )
)

m <- MyClass$new()
m$my_method()

If I set portable = FALSE, or remove parent = self, the code works.

Here's traceback message:

Error in { : could not find function "{" 
5. eval(substitute(expr), data, enclos = parent.frame()) 
4. eval(substitute(expr), data, enclos = parent.frame()) 
3. with.default(self$inner_env, {
    a <- 1
}) 
2. with(self$inner_env, {
    a <- 1
}) 
1. m$my_method() 
wch commented 7 years ago

That happens because the parent environment of self is the empty environment. Basic things like { are found in the base environment, but it is not an ancestor of self, so if you evaluate code in self, it won't find {, or <-. Using local should work fine, though.