【发布时间】:2011-12-15 15:49:39
【问题描述】:
昨天我从 Bill Venables 那里了解到 local() 如何帮助创建静态函数和变量,例如,
example <- local({
hidden.x <- "You can't see me!"
hidden.fn <- function(){
cat("\"hidden.fn()\"")
}
function(){
cat("You can see and call example()\n")
cat("but you can't see hidden.x\n")
cat("and you can't call ")
hidden.fn()
cat("\n")
}
})
在命令提示符下的行为如下:
> ls()
[1] "example"
> example()
You can see and call example()
but you can't see hidden.x
and you can't call "hidden.fn()"
> hidden.x
Error: object 'hidden.x' not found
> hidden.fn()
Error: could not find function "hidden.fn"
我在Static Variables in R 中看到过这种事情,其中采用了不同的方法。
这两种方法的优缺点是什么?
【问题讨论】:
标签: r closures local static-variables