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?