Home > Net >  Capturing ellipsis arguments from within an internal function
Capturing ellipsis arguments from within an internal function

Time:10-15

I'm trying to extract arguments passed to ... from within an internal function to perform validity check. Since the only purpose of the function is to check ellipsis, I'd like the function to have no parameter and capture the ellipsis from the parent function internally.

Here's a simple example of what I'd like to do:

check_dots <- function() {
  # capture ... arguments here
  if (rlang::dots_n(...) == 1L && ... == "foo") {
    stop()
  }
}

(function(...) {
  check_dots()
  "success"
})("foo", "bar")

I've tried using formals(fun = rlang::caller_fn()) to extract ... arguments without success.

CodePudding user response:

The following, using base R, does what you want:

check_dots = function () {
  call = match.call(definition = sys.function(-1L), call = sys.call(-1L), expand.dots = FALSE)
  if (length(call$...) == 1L && call$...[[1L]] == 'foo') stop('error')
}

‘rlang’ has caller_call as an rough equivalent of match.call, but it’s missing an option to prevent expanding dots, so I don’t know how to do the same as above using ‘rlang’.

  • Related