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?
In order to implement lexical scoping, the internal state of a JavaScript function object must include not only the code of the function but also a reference to the current scope chain.
To get correct lexical scoping and closures in an interpreter, all you need to do is follow these rules: In your interpreter, variables are always looked up in an environment table passed in by the caller or kept as a variable, not some global env-stack.
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.
So the "scope of a function" could mean two things: either the scope defined by the function's body, in which its local variables are declared; or the scope (either a class or a namespace) in which the function name is declared.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With