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 ?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top