landau
landau

Reputation: 5841

ignore parent/ancestor environments inside function (disable lexical scoping)

Is there a way to disable lexical scoping in R? I want to prevent a function from using any of its parent/ancestor environments. The desired behavior is an error below (x not found).

x <- 1
f <- function() 
  eval(parse(text = "x"), 
       envir = new.env(), 
       enclos = new.env())
f() # returns 1

Upvotes: 0

Views: 122

Answers (1)

MrFlick
MrFlick

Reputation: 206197

You can set the environment of your function to be the baseenv() which will not search the global environment

x <- 1
f <- function() return(x);
environment(f) <- baseenv()
f() 
# Error in f() : object 'x' not found

This doesn't "disable" lexical scoping so much as it changes the search to skip the global environment.

You can use baseenv() with the eval(envir=) or new.env(parent=) parameters if you need to.

x <- 1
f <- function() 
  eval(parse(text = "x"), 
       envir = baseenv())
f()
# Error in eval(expr, envir, enclos) : object 'x' not found

Upvotes: 4

Related Questions