5

I am looking for ways to emulate 'static' variables within R functions. (I know R is not a compiled language... hence the quotes.) With 'static' I mean that the 'static' variable should be persistent, associated to and modifiable from within the function.

My main idea is to use the attr function:

# f.r

f <- function() {
  # Initialize static variable.
  if (is.null(attr(f, 'static'))) attr(f, 'static') <<- 0L

  # Use and/or modify the static variable...
  attr(f, 'static') <<- attr(f, 'static') + 1L

  # return something...
  NULL
}

This works well, as long as attr can find f. In some scenario's this is no longer the case. E.g.:

sys.source('f.r', envir = (e <- new.env()))
environment(e$f) <- .GlobalEnv
e$f() # Error in e$f() : object 'f' not found

Ideally I would use attr on the 'pointer' of f from within f. sys.function() and sys.call() come to mind, but I do not know how to use these functions with attr.

Anyone ideas or better design patterns on how to emulate 'static' variables within R functions?

Davor Josipovic
  • 4,848
  • 1
  • 34
  • 54

1 Answers1

4

Define f within a local like this:

f <- local({ 
  static <- 0
  function() { static <<- static + 1; static }
})
f()
## [1] 1
f()
## [1] 2
G. Grothendieck
  • 233,926
  • 16
  • 195
  • 321