diff --git a/R/internals_RLum.R b/R/internals_RLum.R index a5501f520..d2cecb584 100644 --- a/R/internals_RLum.R +++ b/R/internals_RLum.R @@ -1335,6 +1335,28 @@ SW <- function(expr) { } } +#' @title Validate logical scalar variables +#' +#' @param val [numeric] (**required**): value to validate +#' @param null.ok [logical] (*with default*): whether a `NULL` value should be +#' considered valid (`FALSE` by default) +#' @param name [character] (*with default*): variable name to report in case +#' of error: if specified, it's reported as is; if not specified it's +#' inferred from the name of the variable tested and reported with +#' quotes. +#' +#' @md +#' @noRd +.validate_logical_scalar <- function(val, null.ok = FALSE, name = NULL) { + if (missing(val) || is.null(val) && null.ok) + return() + if (!is.logical(val) || length(val) != 1 || is.na(val)) { + if (is.null(name)) + name <- sprintf("'%s'", all.vars(match.call())[1]) + .throw_error(name, " should be a single logical value") + } +} + #' Check that a suggested package is installed #' #' Report a message with installation instructions if a suggested package diff --git a/tests/testthat/test_internals.R b/tests/testthat/test_internals.R index 8fafe1553..7205c20f9 100644 --- a/tests/testthat/test_internals.R +++ b/tests/testthat/test_internals.R @@ -380,6 +380,25 @@ test_that("Test internals", { expect_error(.validate_positive_scalar(NA, int = TRUE, name = "The variable"), "The variable should be a positive integer") + ## .validate_logical_scalar() --------------------------------------------- + expect_silent(.validate_logical_scalar()) + expect_silent(.validate_logical_scalar(TRUE)) + expect_silent(.validate_logical_scalar(FALSE)) + expect_silent(.validate_logical_scalar(NULL, null.ok = TRUE)) + + expect_error(.validate_logical_scalar(test <- "a"), + "'test' should be a single logical value") + expect_error(.validate_logical_scalar(test <- NULL), + "'test' should be a single logical value") + expect_error(.validate_logical_scalar(iris), + "'iris' should be a single logical value") + expect_error(.validate_logical_scalar(c(TRUE, FALSE), name = "'var'"), + "'var' should be a single logical value") + expect_error(.validate_logical_scalar(0, name = "'var'"), + "'var' should be a single logical value") + expect_error(.validate_logical_scalar(NA, name = "The variable"), + "The variable should be a single logical value") + ## .require_suggested_package() ------------------------------------------- expect_true(.require_suggested_package("utils")) expect_error(.require_suggested_package("error"),