diff --git a/R/nargin.R b/R/nargin.R index e843e87..6ff20cc 100644 --- a/R/nargin.R +++ b/R/nargin.R @@ -3,9 +3,8 @@ #' @return An integer #' @author Waldir Leoncio #' @note This function only makes sense inside another function +#' @references https://stackoverflow.com/q/64422780/1169233 nargin <- function() { - # FIXME: returning 0 because it is using its own envir instead of parent's - print(parent.env(environment())) - length(as.list(match.call(envir = parent.env(environment())))) - 1 - # length(ls(envir=parent.env(environment()))) - 1 -} \ No newline at end of file + if(sys.nframe() < 2) stop("must be called from inside a function") + length(as.list(sys.call(-1))) - 1 +} diff --git a/man/nargin.Rd b/man/nargin.Rd new file mode 100644 index 0000000..a7922a6 --- /dev/null +++ b/man/nargin.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/nargin.R +\name{nargin} +\alias{nargin} +\title{Number of function input arguments} +\usage{ +nargin() +} +\value{ +An integer +} +\description{ +Returns the number of arguments passed to the parent function +} +\note{ +This function only makes sense inside another function +} +\references{ +https://stackoverflow.com/q/64422780/1169233 +} +\author{ +Waldir Leoncio +} diff --git a/tests/testthat/test-convertedBaseFunctions.R b/tests/testthat/test-convertedBaseFunctions.R index bfc3fe8..11988f8 100644 --- a/tests/testthat/test-convertedBaseFunctions.R +++ b/tests/testthat/test-convertedBaseFunctions.R @@ -201,4 +201,20 @@ test_that("isspace works as expected", { X <- '\t a b\tcde f' expect_identical(isspace(chr), c(0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0)) expect_identical(isspace(X), c(1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0)) +}) + +test_that("nargin works correctly", { + addme <- function(a, b) { + if (nargin() == 2) { + c <- a + b + } else if (nargin() == 1) { + c <- a + a + } else { + c <- 0 + } + return(c) + } + expect_equal(addme(13, 42), 55) + expect_equal(addme(13), 26) + expect_equal(addme(), 0) }) \ No newline at end of file