就像我们拥有可以使用的debugonce
代替debug
/undebug
夫妇一样,使用traceonce
函数而不是trace
/untrace
。
我们该怎么做?
这就是我想到的:
traceonce <- function(what, tracer, exit, at, print, signature,
where = topenv(parent.frame()), edit = FALSE){
mc <- match.call()
mc[[1]] <- quote(trace)
mc[["exit"]] <-
if (missing(exit)) substitute(quote(eval.parent(quote(untrace(what)))))
else c(as.expression(exit), substitute(eval.parent(quote(untrace(what)))))
eval.parent(mc)
}
我编辑了调用的形式,这样我就不必在missing
上处理一堆检查,然后我编辑呼叫的exit
元素(是否存在2个情况,是否存在(即可添加一个呼叫呼叫给定功能。
使用exit
参数:
traceonce(head, exit = quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on exit
#> [1] "hello"
#> Untracing function "head" in package "utils"
#> speed dist
#> 1 4 2
head(cars,1)
#> speed dist
#> 1 4 2
没有exit
参数:
traceonce(head, quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on entry
#> [1] "hello"
#> Tracing head(cars, 1) on exit
#> Untracing function "head" in package "utils"
#> speed dist
#> 1 4 2
head(cars,1)
#> speed dist
#> 1 4 2