Last active
May 22, 2020 04:06
-
-
Save seasmith/4e6f0e4c87d6d31e3d8f1c1c863e5eea to your computer and use it in GitHub Desktop.
Understanding environments and frames
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# What you need to know: | |
# * environments -- inheritance of definition | |
# * frames -- call reference | |
# | |
# What does that mean? | |
# * environments are inherited when a function is defined (i.e. f <- function () {}) | |
# * frames refer to where a function was called from, not where it was defined | |
i <- 1 | |
# This demonstrates environment inheritance | |
f1 <- function (x) { | |
print(exists("i")) | |
print(parent.env(environment())) | |
j <- 2 | |
function (y) { | |
print(exists("j")) | |
print(parent.env(environment())) | |
k <- 3 | |
function (z) { | |
print(exists("k")) | |
print(parent.env(environment())) | |
ls() | |
} | |
} | |
} | |
f2 <- f1(10) | |
f3 <- f2(100) | |
# This demonstrates the call stack | |
f1 <- function (x) { | |
print(exists("i")) | |
print(sys.parent()) # <-- 0 | |
(function() {print(sys.parent())})() # <-- 1 | |
j <- 2 | |
function (y) { | |
print(exists("j")) | |
print(sys.parent(2)) # <-- 0 | |
k <- 3 | |
function (z) { | |
print(exists("k")) | |
print(sys.parent(3)) # <-- 0 | |
ls() | |
} | |
} | |
} | |
f2 <- f1(10) | |
f3 <- f2(100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment