defer: Defer Evaluation of an Expression

Description Usage Arguments Details See Also Examples

Description

Similar to on.exit(), but allows one to attach an expression to be evaluated when exitting any frame currently on the stack. This provides a nice mechanism for scoping side effects for the duration of a function's execution.

Usage

1
2
3
defer(expr, envir = parent.frame(), priority = c("first", "last"))

defer_parent(expr, priority = c("first", "last"))

Arguments

expr

An expression to be evaluated.

envir

Attach exit handlers to this environment. Typically, this should be either the current environment or a parent frame (accessed through parent.frame()).

priority

Specify whether this handler should be executed "first" or "last", relative to any other registered handlers on this environment.

Details

defer works by attaching handlers to the requested environment (as an attribute called "handlers"), and registering an exit handler that executes the registered handler when the function associated with the requested environment finishes execution.

See Also

Other scope-related functions: scope_dir, scope_env_vars, scope_locale, scope_options, scope_path

Examples

 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
# define a 'scope' function that creates a file, and
# removes it when the parent function has finished executing
scope_file <- function(path) {
  file.create(path)
  defer_parent(unlink(path))
}

# create tempfile path
path <- tempfile()

# use 'scope_file' in a function
local({
  scope_file(path)
  stopifnot(file.exists(path))
})

# file is deleted as we leave 'local' scope
stopifnot(!file.exists(path))

# investigate how 'defer' modifies the
# executing function's environment
local({
  scope_file(path)
  print(attributes(environment()))
})

kevinushey/later documentation built on May 20, 2019, 9:09 a.m.