【发布时间】:2021-07-28 08:47:58
【问题描述】:
我正在尝试了解函数内部的 eval 函数行为,因此假设这是我的设置:
定义了两个全局变量 x 和 a
x <- 'a'
a <- 'c'
然后用三个打印语句定义了一个函数 f,我对 eval、envir 参数默认为 parent.frame() 的事实感到困惑,但是,如果我故意说出来,结果会有所不同。为什么?
下面是与cmets一起理解的代码,非常感谢cmets提前解决这个问题。
f <- function(x){
## 1st statement, I get it that evaluation should be done in current environment
print(eval(quote(x), envir = environment()))
## 2nd statement, This I don't get, as the default is parent.frame(), shouldn't it be
## evaluated in the calling scope of function which is global environment. As per
## documentation parent.frame() is the default then why this result evaluates to current
## environment, whereas the last print statement when specifically mentions parent.frame gives a different result entirely.
## Note the documentation says: If envir is not specified, then the default is parent.frame() (the environment where the call to eval was made).
## So, my understanding of parent.frame is that it is that frame where calls are happening(basically calling environment), Am I mistaken here?
print(eval(quote(x)))
## 3rd , This behaviour seems okay as parent.frame is referencing the calling scope which is global
print(eval(quote(x), envir=parent.frame()))
}
输出:
#> f(a) #[1] "c" #[1] "c" #[1] "a"
【问题讨论】: