Consider the function with functions below:
f1=function(){
f3=function() print(a)
f2=function() {
print(a)
a=3
f3()}
print(a)
a=2
f2()
a=1
f1()
[1] 1
[1] 2
[1] 2
Why does f2()
consider f1()
its parent environment but f3()
does not consider f2()
its parent environment? I expect f3()
printing 3
, set on f2()
, rather than 2
.
If a variable is defined inside f2()
, f3()
can not find it:
f1=function(){
f3=function() print(b)
f2=function() {
print(a)
b=3
f3()}
print(a)
a=2
f2()
a=1
f1()
[1] 1
[1] 2
Error in print(b) : object 'b' not found