rlang (version 0.1)

stack_trim: Trim top call layers from the evaluation stack

Description

ctxt_stack() can be tricky to use in real code because all intervening frames are returned with the stack, including those at ctxt_stack() own call site. stack_trim() makes it easy to remove layers of intervening calls.

Usage

stack_trim(stack, n = 1)

Arguments

stack

An evaluation stack.

n

The number of call frames (not eval frames) to trim off the top of the stack. In other words, the number of layers of intervening frames to trim.

Examples

Run this code
# NOT RUN {
# Intervening frames appear on the evaluation stack:
identity(identity(ctxt_stack()))

# stack_trim() will trim the first n layers of calls:
stack_trim(identity(identity(ctxt_stack())))

# Note that it also takes care of calls intervening at its own call
# site:
identity(identity(
  stack_trim(identity(identity(ctxt_stack())))
))

# It is especially useful when used within a function that needs to
# inspect the evaluation stack but should nonetheless be callable
# within nested calls without side effects:
stack_util <- function() {
  # n = 2 means that two layers of intervening calls should be
  # removed: The layer at ctxt_stack()'s call site (including the
  # stack_trim() call), and the layer at stack_util()'s call.
  stack <- stack_trim(ctxt_stack(), n = 2)
  stack
}
user_fn <- function() {
  # A user calls your stack utility with intervening frames:
  identity(identity(stack_util()))
}
# These intervening frames won't appear in the evaluation stack
identity(user_fn())
# }

Run the code above in your browser using DataCamp Workspace