Search code examples
rfunctionreturnenvironment

R - evaluating return() in parent environment


I'd need an "inside" function to return as if it were the parent function.

Example:

some_fn <- function() {
  inside_fn <- function() {
    eval.parent(return("I wish"))
  }
  inside_fn()
  return("I wish not")
}

some_fn()
## [1] "I wish not"

Using stop() with on.exit() works...

some_fn_2 <- function() {
  on.exit(return("Well, this works"))
  inside_fn <- function() {
    eval.parent(return("I wish"))
    stop()
  }
  inside_fn()
  return("I wish not")
}

some_fn_2()
[1] "Well, this works"

... but is sort of hackish and I wonder if there is a cleaner way to do this. I know it's not exactly simple; it would imply ignoring part of the call stack, but still, I'd like to know your thoughts, dear community. :)


Solution

  • callCC can break out of nested calls:

    callCC(function(k) {
      inside_fn <- function() {
        k("I wish")
      }
      inside_fn()
      return("I wish not")
    })
    ## [1] "I wish"