Question

Sourcing this code:

a <- F
f1 <- function() a
f2 <- function() {
  a <- T
  eval(f1())
}

and calling f2() will return FALSE.

How to modify the arguments for the eval so that f2() will return TRUE ?

Was it helpful?

Solution

You can do this:

a <- F
f1 <- function() a
f2 <- function() {
  a <- T
  environment(f1) <- new.env()
  eval(f1())
}
f2()
# [1] TRUE

Though I wouldn't encourage it. What we've done here is changed the environment of f1 to be one which has for enclosure f2's environment, which means f1 will have access to f2s variables through "lexical" scoping (well, faux-lexical here b/c we short circuited it).

Generally, as Roman suggests, you should explicitly pass arguments to functions as otherwise you can quickly run into trouble.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top