문제

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