Skip to content
Prev 256323 / 398506 Next

best practice(s) for retrieving a local variable from a closure

You can also use a list-like notation with environments:
  > environment(f2)$a
  [1] 2
  > environment(f2)[["a"]]
  [1] 2
  > environment(f2)$a <- 3:1
  > f2(2)
  [1] 8 4 2

The above feels a bit like snooping where I wasn't invited.
You could do something like
  mq <- function(a) {
     force(a)
     list(getA = function()a,
          setA = function(newA) a <<- newA,
          fun = function(x)x^a
     )
  }
to make it clear that you expect people to look at or change
fun's 'a'.
  > f3 <- mq(3)
  > f3$fun(5)
  [1] 125
  > f3$getA()
  [1] 3
  > f3$setA(4:1)
  > f3$fun(3)
  [1] 81 27  9  3

I don't code like this much so haven't developed a sense of
aesthetics about these variants.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com