Skip to content

Instantly share code, notes, and snippets.

@seasmith
Last active May 22, 2020 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seasmith/4e6f0e4c87d6d31e3d8f1c1c863e5eea to your computer and use it in GitHub Desktop.
Save seasmith/4e6f0e4c87d6d31e3d8f1c1c863e5eea to your computer and use it in GitHub Desktop.
Understanding environments and frames
# 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