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?