1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/vars.R
\name{poke_vars}
\alias{poke_vars}
\alias{scoped_vars}
\alias{with_vars}
\alias{has_vars}
\title{Replace or get current variables}
\usage{
poke_vars(vars)
scoped_vars(vars, frame = caller_env())
with_vars(vars, expr)
has_vars()
}
\arguments{
\item{vars}{A character vector of variable names.}
\item{frame}{The frame environment where the exit hook for
restoring the old variables should be registered.}
\item{expr}{An expression to be evaluated within the variable
context.}
}
\value{
For \code{poke_vars()} and \code{scoped_vars()}, the old variables
invisibly. For \code{peek_vars()}, the variables currently
registered.
}
\description{
Variables are made available to \link[=language]{select helpers} by
registering them in a special placeholder.
\itemize{
\item \code{scoped_vars()} changes the current variables and sets up a
function exit hook that automatically restores the previous
variables once the current function returns.
\item \code{with_vars()} takes an expression to be evaluated in a variable
context.
\item \code{poke_vars()} changes the contents of the placeholder with a new
set of variables. It returns the previous variables invisibly and
it is your responsibility to restore them after you are
done. This is for expert use only.
\item \code{peek_vars()} returns the variables currently registered.
\item \code{has_vars()} returns \code{TRUE} if a variable context has been set,
\code{FALSE} otherwise.
}
}
\examples{
poke_vars(letters)
peek_vars()
# Now that the variables are registered, the helpers can figure out
# the locations of elements within the variable vector:
all_of(c("d", "z"))
# In a function be sure to restore the previous variables. An exit
# hook is the best way to do it:
fn <- function(vars) {
old <- poke_vars(vars)
on.exit(poke_vars(old))
all_of("d")
}
fn(letters)
fn(letters[3:5])
# The previous variables are still registered after fn() was
# called:
peek_vars()
# It is recommended to use the scoped variant as it restores the
# state automatically when the function returns:
fn <- function(vars) {
scoped_vars(vars)
starts_with("r")
}
fn(c("red", "blue", "rose"))
# The with_vars() helper makes it easy to pass an expression that
# should be evaluated in a variable context. Thanks to lazy
# evaluation, you can just pass the expression argument from your
# wrapper to with_vars():
fn <- function(expr) {
vars <- c("red", "blue", "rose")
with_vars(vars, expr)
}
fn(starts_with("r"))
}
\seealso{
peek_vars
}
\keyword{internal}
|