【发布时间】:2020-03-26 07:46:28
【问题描述】:
我正在寻找在 R 函数中模拟“static”变量的方法。 (我知道 R 不是一种编译语言......因此引用了引号。)对于“静态”,我的意思是“静态”变量应该是持久的、与函数相关联并可以在函数内修改。
我的主要想法是使用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
}
这很好用,只要attr 可以找到f。在某些情况下,情况不再如此。例如:
sys.source('f.r', envir = (e <- new.env()))
environment(e$f) <- .GlobalEnv
e$f() # Error in e$f() : object 'f' not found
理想情况下,我会在f 内的f 的“指针”上使用attr。 sys.function() 和 sys.call() 浮现在脑海中,但我不知道如何将这些功能与 attr 一起使用。
关于如何在 R 函数中模拟“静态”变量的任何想法或更好的设计模式?
【问题讨论】: