1

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 ?

7
  • Specify arguments to functions explicitly and you will not bother with in which environment the function is executed and from where the arguments come from. Commented Mar 1, 2014 at 18:56
  • the reason why I cannot specify f1 with a as argument is because my f1 is in fact Ops.myclass, which has Ops(e1, e2) signature, not Ops(e1, e2, a) signature. What I want to achieve is for Ops to operate on my class with different behaviors depending on value of a Commented Mar 1, 2014 at 19:16
  • In your example a is global, if it is in your real code as well you could assign a using <<- in f2. Or use the assign function to a particular environment... Commented Mar 1, 2014 at 19:19
  • 1
    Since you control myclass, why don't you just add a slot to contain a and pass it that way, or even better, define different sub-classes that invoke different methods depending on what type of a they belong to? Commented Mar 1, 2014 at 19:23
  • @Thell I should have mentioned that that I would not want any accidentally defined "global" a clash with the behavior of f2, which depends on the local a Commented Mar 1, 2014 at 19:30

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I've learned something. For those interested, here is also more background reading on scoping

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.