Reputation: 5131
foo <- function() {
# how to know what environment_of_caller is
}
caller <- function() {
# environment_of_caller
foo()
}
A function that I'm writing needs to the know the environment of its caller. Can that be done without passing the environment in as an argument?
Upvotes: 1
Views: 223
Reputation: 270308
Assuming that you really need to do this, the function parent.frame()
gives it.
foo <- function() {
parent.frame()$a
}
caller <- function() {
a <- 1
foo()
}
caller()
## [1] 1
however, normally one would write it like this (only foo
is changed) as it gives the desired functionality but also the flexibility to change the environment used.
foo <- function(envir = parent.frame()) {
envir$a
}
caller <- function() {
a <- 1
foo()
}
caller()
## [1] 1
Upvotes: 4