0

Here is my example:

library(R6)

SharedVar <- R6Class("SharedVar",
                     public = list(x= NULL)
)

MainClass <- R6Class("MainClass",
                     public = list(
                       name = NULL,
                       shared_var = SharedVar$new(),
                       initialize = function(name = NA){
                         self$name = name
                       },
                       popuate_shared_var = function(foo = NA){
                         shared_var$x = foo
                       }
                       )
                     )

When I run:

test_obj <- MainClass$new(name = "test")
test_obj$popuate_shared_var(foo="some value")

I get back:

Error in shared_var$x = foo : object 'shared_var' not found

but the following works fine and returns NULL:

test_obj$shared_var$x

What am I missing?

user1700890
  • 7,144
  • 18
  • 87
  • 183
  • You seem to be missing the `self$` part in your `popuate_shared_var ` function: `self$shared_var$x = foo` – MrFlick Apr 12 '21 at 21:28
  • Would not `self` make it class instance variable? – user1700890 Apr 12 '21 at 21:39
  • @MrFlick, thank you, sure, but I should be able to use reference obj as class variable: https://r6.r-lib.org/articles/Introduction.html#fields-containing-reference-objects – user1700890 Apr 12 '21 at 21:47
  • 1
    You still need to use `self` to access that object. Just try it. Create a second object and call `popuate_shared_var`. You'll see the value changes in both. – MrFlick Apr 12 '21 at 21:52

1 Answers1

1

You need a self so R knows where to find that shared_var.

library(R6)

SharedVar <- R6Class("SharedVar",
                     public = list(x= NULL)
)

MainClass <- R6Class("MainClass",
                     public = list(
                       name = NULL,
                       shared_var = SharedVar$new(),
                       initialize = function(name = NA){
                         self$name = name
                       },
                       popuate_shared_var = function(foo = NA){
                         self$shared_var$x = foo
                       }
                     )
)

test_obj <- MainClass$new(name = "test")
test_obj$popuate_shared_var(foo="some value")

test_obj$shared_var$x
#> [1] "some value"

Created on 2021-04-12 by the reprex package (v1.0.0)

the-mad-statter
  • 5,650
  • 1
  • 10
  • 20