I've looked at the other lexical scoping questions in R and I can't find the answer. Consider this code:
f <- function(x) {
g <- function(y) {
y + z
}
z <- 4
x + g(x)
}
f(3)
f(3)
will return an answer of 10. My question is why? At the point g()
is defined in the code, z
has not been assigned any value. At what point is the closure for g()
created? Does it "look ahead" to the rest of the function body? Is it created when the g(x)
is evaluated? If so, why?
When f
is run, the first thing that happens is that a function g
is created in f
's local environment. Next, the variable z
is created by assignment.
Finally, x
is added to the result of g(x)
and returned. At the point that g(x)
is called, x = 3
and g
exists in f
's local environment. When the free variable z
is encountered while executing g(x)
, R looks in the next environment up, the calling environment, which is f
's local environment. It finds z
there and proceeds, returning 7. It then adds this to x
which is 3.
(Since this answer is attracting more attention, I should add that my language was a bit loose when talking about what x
"equals" at various points that probably do not accurately reflect R's delayed evaluation of arguments. x
will be equal to 3 once the value is needed.)