Is there a way to run an expression on.exit() but only if completes normally, not on error?

后端 未结 3 1339
情深已故
情深已故 2021-01-08 00:48

I\'m aware of the function on.exit in R, which is great. It runs the expression when the calling function exits, either normally or as the result of an error.

3条回答
  •  青春惊慌失措
    2021-01-08 01:19

    Bit more readable version of my comment on @Joris' answer:

    f = function() {
      ret = local({
        myvar = 42
        if (runif(1) < 0.5)
          return(2)
        stop('oh noes')
      }, environment())
      # code to run on success...
      print(sprintf('myvar is %d', myvar))
      ret
    }
    

提交回复
热议问题