-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathsetup.Rd
More file actions
65 lines (61 loc) · 2.43 KB
/
Copy pathsetup.Rd
File metadata and controls
65 lines (61 loc) · 2.43 KB
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
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/setup.R
\name{setup}
\alias{setup}
\title{Set up per-step state in a coroutine}
\usage{
setup(expr)
}
\arguments{
\item{expr}{An expression to run at the start of each step.}
}
\description{
\code{setup()} registers an expression that runs at the start of \strong{every} step of
a \code{\link[=generator]{generator()}} or \code{\link[=async]{async()}} function: the initial entry and every resumption
after a \code{\link[=yield]{yield()}} or \code{\link[=await]{await()}}. Any \code{withr::defer()}, \verb{withr::local_*()}, or
\code{\link[=on.exit]{on.exit()}} registered while \code{expr} runs is torn down at the \strong{end of that
step} (the next \code{yield}/\code{await}, a \code{return}, normal completion, an error, or
early close).
This gives setup/teardown parity for each step of a coroutine, unlike a
top-level \code{on.exit()} which only fires once when the whole function exits.
}
\details{
\itemize{
\item \code{expr} runs in an isolated environment: it can read the function's
arguments, locals, and lexical scope, and mutate external state
(\code{the$x <- 1}, \verb{<<-}), but \strong{plain assignments stay local to \code{expr}} and are
not visible to the function body.
\item When execution reaches a \code{setup()} call it is registered and runs for the
current step; re-encountering the \emph{same} \code{setup()} call (e.g. on a later loop
iteration) is a no-op. A \code{setup()} inside an \code{if}/loop registers only if and
when reached.
\item Multiple \code{setup()} calls stack and run in registration order each step; their
teardowns fire in reverse order.
\item \code{setup()} cannot contain \code{yield()}/\code{await()} and its result cannot be
assigned.
}
Like \code{\link[=yield]{yield()}} and \code{\link[=await]{await()}}, \code{setup()} is a syntactic construct recognised by
the coroutine compiler. Calling it directly (outside a coroutine body) is an
error.
}
\examples{
the <- new.env()
the$x <- 0
gen <- generator(function() {
setup({
old_x <- the$x
the$x <- 1
on.exit(the$x <- old_x, add = TRUE)
})
yield(the$x) # 1 while the step runs
yield(the$x) # 1 again: setup re-ran for this step
})
g <- gen()
g() # 1
the$x # 0 — restored at the end of the step
g() # 1
the$x # 0
}
\seealso{
\code{\link[=generator]{generator()}}, \code{\link[=async]{async()}}, \code{\link[=yield]{yield()}}, \code{\link[=await]{await()}}.
}