nseval (version 0.5.1)

locate: Find the environment which defines a name.

Description

locate starts at a given environment, and searches enclosing environments for a name. It returns the first enclosing environment which defines sym.

locate_ is the normally evaluating method; locate(x) is equivalent to locate_(quo(x)) or locate_(quote(x), environment()).

When sym is a quotation or dots, any env argument is ignored.

Usage

locate(sym, env = arg_env_(quote(sym), environment()), mode = "any", ...)

locate_(sym, env = arg_env_(quote(sym), environment()), mode = "any", ...)

locate_.list(sym, env = arg_env_(quote(sym), environment()), mode = "any", ...)

locate_.quotation(sym, env = "ignored", mode = "any", ...)

locate_.character( sym, env = arg_env_(quote(sym), environment()), mode = "any", ... )

`locate_.(`(sym, env = arg_env_(quote(sym), environment()), mode = "any", ...)

locate_.dots(sym, env = "ignored", mode = "any", ...)

locate_.name( sym, env = arg_env_(quote(sym), environment()), mode = "any", ifnotfound = stop("Binding ", deparse(sym), " not found") )

Value

An environment object which defines sym, if one is found.

If sym is a list (of names) or a dots object, locate_(sym)

returns a list.

Arguments

sym

A name. For locate the argument is used literally. For locate_ it should be a name or list of names.

env

Which environment to begin searching from.

mode

Either "any" or "function". "any" finds the lowest enclosing environment which gives any definiton for sym. "function" searches for an environment which defines sym as a function. This may force lazy arguments in the process, in the same way as get.

...

Further arguments passed to methods.

ifnotfound

What is returned if the symbol is not found. By default an exception is raised.

Examples

Run this code
# Here is how to implement R's `<<-` operator, using `locate_`:
`%<<-%` <- function(lval, rval) {
  lval_ <- arg(lval)
  name <- expr(lval_)
  target.env <- locate_(name, parent.env(env(lval_)))
  assign(as.character(name), rval, envir=target.env)
}

x <- "not this one"
local({
  x <- "this one"
  local({
    x <- "not this one either"
    x %<<-% "this works like builtin <<-"
  })
  print(x)
})
print(x)

Run the code above in your browser using DataLab