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")
)Arguments
- sym
A name. For
locatethe argument is used literally. Forlocate_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 forsym."function"searches for an environment which definessymas 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.
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.
Note
To locate where ... is bound, you can wrap it in parens, as
locate( (...) ).
If you use a literal character argument, as in locate("x", environment()), you must also provide the environment argument
explicitly; locate("x") won't work in compiled
functions. However using a literal name like locate(x) will
work OK. See note under arg.
Examples
# 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)
})
#> [1] "this works like builtin <<-"
print(x)
#> [1] "not this one"