You are being tripped up by the subtle differences between frames and environments (which is even more subtle since frames are environments, or maybe environments are frames) and the difference between lexical and dynamic scoping. There are some details in the help page for parent.frame
and other places spread across various documentation.
To try and simplify:
Your getter
function has its own environment where variables local to that function are stored (x
in this case). Since R is lexically scoped that means that the functions environment has a parent environment which is defined by where the function is defined, the global environment in this case (if it were defined inside of another function then the parent environment would be the env for that function).
When you call f1
and it calls getter
then getter tries to find the variable foo
, it first looks in its own environment, does not find it there, then looks in its parent environment which is the global env and finds foo
with the value of 1.
Your thinking goes along the lines of dynamic scoping, which the frames approximate. When f1
is called it gets its own environment (within which foo
will be assigned the value 2), then it calls the getter
function. The environment of foo
is not the parent of getter
's env (lexical scoping), but the environment of f1
is the parent frame of getter
since getter
was called from f1
, so to look in the environment of f1
you need to tell the get
function to look in the parent frame rather than the parent environment.
The summary of this is that the parent environment is the environment where a function was defined (lexical scoping), the parent frame is the frame/environment from which the function was called (simulated dynamic scoping).