match_arg: Match a function's argument against candidates

Description Usage Arguments Details Value Examples

View source: R/match-arg.R

Description

Function match_arg() is a safer, more flexible alternative to match.arg().

  1. It expects scalar values only.

  2. It only works when called by another function.

  3. A default value can be explicitly defined as such.

  4. In case of no match, the error message is customizable, and prettier by default.

Usage

1
match_arg(arg, error = NULL, ..., ..force_empty_stack = FALSE)

Arguments

arg

[atomic(1)]

The argument to match. It is passed to pmatch() and is eventually converted to a character vector by this function.

error

[character(1)]

Passed to ui_stop(). See details.

...

[any]

Further calls passed to ui_stop(). See details.

..force_empty_stack

[logical(1)]

Never ever use that argument. This is a flag only relevant when debugging and testing match_arg().

Details

When customizing error messages via error and/or ..., you must ensure that any expression(s) embedded into these error messages are properly evaluated in their own scope before being passed down to match_arg(). Else, you will get an error. See examples.

Value

An atomic(1). Its type matches types of arg.

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
26
27
28
29
30
31
## It always fails when called outside of another function.
## Not run: match_arg()

## It matches the usual behavior of match.arg().
wrap <- function(foo = c("a", "b", "c")) {
    return(match_arg(foo))
}

identical(wrap(),    "a")
identical(wrap("b"), "b")

## Error messages are much more beautiful and match dotprofile's styling.
## Not run: wrap("d")

## You can explicitly mark a value as being the default one.
wrap2 <- function(foo = c("a", "b", default = "c")) {
    return(match_arg(foo))
}

identical(wrap2(),    "c")
identical(wrap2("b"), "b")

## Customize error messages.
wrap3 <- function(foo = c("a", "b", default = "c")) {
    error <- cli::format_inline("{.arg {foo}} contains an error.")
    return(
        match_arg(foo, error,
            ui_todo("It must be equal to a valid value.")))
}

## Not run: wrap3("d")

jeanmathieupotvin/dotprofile documentation built on Dec. 20, 2021, 10:08 p.m.