Skip to content

help with eval

3 messages · Whit Armstrong, Gabor Grothendieck, Brian Ripley

#
The scope of variables within show.a is not affected by the environment
that show.a is called in.  The scope of the variables in show.a
is determined by the lexical scope of show.a although you can change 
this via:

  environment(show.a) <- my.env
  show.a() # 200

If you want to create a function that has dynamic (i.e. scope is the caller), 
rather than lexical scope, do this:

   show2.a <- function() { 
      show2.a <- function() a 
      environment(show2.a) <- parent.frame()
      show2.a()
   }
  evalq(show2.a(), my.env) # 200

or you can create a function which evaluates its body in the parent.frame:

   show3.a <- function() eval.parent(substitute(a))
   evalq(show3.a(), my.env) # 200

Also, depending on what you actually want to do, the proto package
may be applicable.
On 5/13/05, Whit Armstrong <whit at twinfieldscapital.com> wrote:
#
You intended quote() rather than expression(), I believe.  If I do
this works.

R has lexical scoping, so with
'a' is looked for in the frame of the function (not defined there) and 
then in the environment of the function.
<environment: R_GlobalEnv>

since show.a was defined in the workspace.  The envir arg of eval() is 
used to find the object(s), here `show.a', not to sets its environment.
So my first version works because 'a' is part of the expression.

Perhaps you intended something like

init.env <- function() {
  a <- 200
  show.a <- function() {a}
  environment()
}
my.env <- init.env()
eval(quote(show.a()),envir=my.env)

which works, and is a common R idiom (although via local() or new.env()).

However, you could just do
[1] 200
[1] 200

BTW, use typeof() to see the difference here.
On Fri, 13 May 2005, Whit Armstrong wrote: