adv-r icon indicating copy to clipboard operation
adv-r copied to clipboard

Other possible style to use `on.exit`

Open hope-data-science opened this issue 2 years ago • 2 comments
trafficstars

I've learned on.exit in the book and it is really helpful. But setting the parameter add to TRUE get me a little puzzled, and the after argument might just make it harder to know the order of expressions. If the contents in on.exit would just run in the end, why not wrap them up? Which mean:

j08 <- function() {
  on.exit(message("a"), add = TRUE)
  on.exit(message("b"), add = TRUE)
}

could be used as:

j08 <- function() {
    on.exit({message("a");message("b")})
}

In this style, we do not have to figure out which codes would be evaluated first. Wonder if this style would be better.

Thanks.

hope-data-science avatar Feb 03 '23 03:02 hope-data-science

Imagine R keeps a list of commands which need to be executed when exiting. The current implementation allows you to do one of three things:

  • Place commands at the end of the list (add=TRUE, after=TRUE)
  • Place commands at the beginning of the list (add=TRUE, after=FALSE)
  • Replace the list (add=FALSE, after=TRUE or after=FALSE)

What you have suggested is not wrong, and it even makes sense if you only call on.exit once in your program, but the arguments of on.exit are there to support the more general functionality described above.

jfunction avatar Feb 20 '23 08:02 jfunction

I can understand your point, some on.exit might only be executed on condition. In these cases, the argument add and after could be used flexibly.

hope-data-science avatar Feb 21 '23 04:02 hope-data-science