get_fun_env: Return the execution environment of a function

Description Usage Arguments Details Value Examples

View source: R/get_fun_env.r

Description

Return the execution environment of a function by going over the execution environments of all functions in the calling chain.

Usage

1
get_fun_env(fun_name_or_address)

Arguments

fun_name_or_address

string containing either the name of the function of interest or the memory address of the execution environment to retrieve (N.B. this sould not be the memory address of the function itself, but the memory address of its execution environment). When the function name is given, it should be given with its full path, i.e. including the environment where it is defined (e.g. "env1$f") and with no arguments.

Details

This function is expected to be called from within a function. Otherwise, the function calling chain is empty and the function returns NULL.

Value

When the input parameter is a memory address, the execution environment of the function whose memory address (of the execution environment) equals the given memory address.

When the input parameter is a function name, a list of ALL the execution environments belonging to a function whose name coincides with the given name (including any given path). Note that these may be many environments as the same function may be called several times in the function calling chain.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Define the function that is called to show the behaviour of get_fun_env()
h <- function(x) {
  # Get the value of parameter 'x' in the execution environment of function 'env1$g'
  # If function 'env1$g' is not found, 'x' is evaluated in the current environment or function
  xval = evalq(x, get_fun_env("env1$g")[[1]])
  return(xval)
}
# Define the function that calls h() in a user-defined environment 
env1 <- new.env()
with(env1, 
  g <- function(y) {
    x = 2
    return( h(y) )
  }
)
# Call env1$g()
cat("The value of variable 'x' inside env1$g is", env1$g(3), "\n") 
  ## Prints '2', because the value of x inside env1$g() is 2
  ## ('3' is the value of variable 'y' in env1$g(), not of variable 'x')

# When get_fun_env() is called from outside a function, it returns NULL
get_fun_env("env1$g")  # NULL, even if function 'g' exists,
                       # but we are not calling get_fun_env() from a function

envnames documentation built on Dec. 8, 2020, 9:07 a.m.