在 R 函数中模拟静态变量

Dav*_*vic 5 static r

我正在寻找在 R 函数中模拟“静态”变量的方法。(我知道 R 不是编译语言......因此是引号。)对于 'static' 我的意思是 'static' 变量应该是持久的,与函数相关联并且可以从函数内部修改。

我的主要想法是使用该attr功能:

# 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
}
Run Code Online (Sandbox Code Playgroud)

这很好用,只要attr能找到f。在某些情况下,情况不再如此。例如:

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

理想情况下,我会attrffrom inside的“指针”上使用fsys.function()sys.call()浮现在脑海中,但我不知道如何使用这些功能用attr

关于如何在 R 函数中模拟“静态”变量的任何想法或更好的设计模式?

G. *_*eck 5

f在这样的内部定义local

f <- local({ 
  static <- 0
  function() { static <<- static + 1; static }
})
f()
## [1] 1
f()
## [1] 2
Run Code Online (Sandbox Code Playgroud)