有没有一种方法可以将闭包复制到一个新对象,该对象包含原始闭包的当前状态,同时还可以针对环境中所有即将发生的更改进行分离?
我试图提出一个解决方案,但当我尝试使用包含的函数时,它失败并出现错误:
Error in { : could not find function "{"
这是一个代码示例:
# basic incrementation closure
inc <- function() {
i <- 0
function(x = 1) {
i <<- i + x
i
}
}
copyClosure <- function(x) {
oldEnv <- environment(x)
# set up copy of x in new env
ret <- x
newEnv <- new.env(parent = emptyenv())
environment(ret) <- newEnv
# copy objects from old to new env
objs <- ls(envir = oldEnv, all.names = TRUE, sorted = FALSE)
for (ii in objs) assign(x = ii, envir = newEnv, value = get(x = ii, envir = oldEnv))
return(ret)
}
# original closure object
foo <- inc()
foo(5)
bar <- copyClosure(foo)
# check if objects i are identical
identical(x = get(x = "i", envir = environment(foo)),
y = get(x = "i", envir = environment(bar)))
# check if objects i are separated
foo(5)
identical(x = get(x = "i", envir = environment(foo)),
y = get(x = "i", envir = environment(bar)))
# try using copied closure
bar(5)
更改新环境的父环境以匹配旧环境
newEnv <- new.env(parent = parent.env(oldEnv))
然后它似乎按预期工作。