[R] lexical scope
Thomas Lumley
tlumley at u.washington.edu
Tue Apr 22 15:45:06 CEST 2003
On Tue, 22 Apr 2003, Laurent Gautier wrote:
> On Tue, Apr 22, 2003 at 04:07:39PM +1200, Robin Hankin wrote:
> > Hi everyone
> >
> > another documented feature that was a bit unexpected for me:
> >
> > R> x <- 19
> > R> f <- function(t){t+x}
> > R> f(100)
> > [1] 119
> >
> > --as expected: x is visible from within f()
> > ..but...
> >
> >
> > R> g <- function(a){x <- 1e99 ; return(f(a))}
> > R> g(4)
> > [1] 23
> >
> > --the "x" that is visible from within g() is just 19, which is not the
> > one I expected it to find.
> >
Yes. R has lexical, not dynamic, scope. That is, the lookup depends on
where a function was defined, not where it was called from.
If you need to fake dynamic scope then
a) Try not to
b) Use eval.parent()
-thomas
More information about the R-help
mailing list