hadley / adv-r

Advanced R: a book
http://adv-r.hadley.nz
Other
2.36k stars 1.71k forks source link

Other possible style to use `on.exit` #1758

Open hope-data-science opened 1 year ago

hope-data-science commented 1 year ago

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.

jfunction commented 1 year ago

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:

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.

hope-data-science commented 1 year ago

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.