R - 在父环境中评估 return()

R - evaluating return() in parent environment

我需要一个 "inside" 函数来 return 就好像它是父函数一样。

示例:

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

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

stop()on.exit() 结合使用...

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"

...但是有点老套,我想知道是否有更简洁的方法来做到这一点。我知道这并不简单;这意味着忽略部分调用堆栈,但是,亲爱的社区,我仍然想知道你的想法。 :)

callCC 可以跳出嵌套调用:

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