1

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. :)

Dominic Comtois
  • 10,230
  • 1
  • 39
  • 61
  • I don't think your second example "works": it will never return `"I wish not"`, whether `inside_fn` asks for a special return or not. – user2554330 Jan 13 '19 at 21:41
  • Good point. But in my present situation, it doesn't really matter. The return value will always be the same... I just want control over the moment it is returned, without having to "check if I can return now" after every operation. The inside function's role is precisely that. – Dominic Comtois Jan 13 '19 at 21:46
  • But you don't have that control. *Both* return calls are executed. You can see this if you change `return("I wish not")` to `cat("I wish not")`. – user2554330 Jan 13 '19 at 22:31
  • Okay this seems pretty weird to me. I always thought `stop()` meant "stop"! – Dominic Comtois Jan 13 '19 at 22:40

1 Answers1

3

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"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341