如何仅在满足条件时启动调试器 [英] How to start debugger only when condition is met
问题描述
假设我有一个函数,该函数使用整数 i
上的循环.现在出了点问题,我认为错误发生在 i = 5
时.现在,我可以逐步完成每一个步骤(到目前为止,我所做的事情).
Assume I have a function which uses a loop over integer i
. Now something goes wrong and I assume the error happens when i=5
. Now I can step through every single step (what I did up to now).
但是现在我了解了 browser
和 debug
的 condition
和 text
参数:
But now I read about the condition
and text
argument of browser
and debug
:
文本是可以在浏览器为已输入.
condition 条件,可以在浏览器中检索到输入.
text a text string that can be retrieved when the browser is entered.
condition a condition that can be retrieved when the browser is entered.
是否可以按照我想要的方式使用参数?
Is it possible to use the arguments in a way it works as I want?
这里是一个例子.调试器/浏览器应仅在达到 i = 5
后启动:
Here is an example. The debugger / browser should only start after i=5
is reached:
fun <- function(x, y, n) {
result <- 0
for (i in 1:n) {
# browser(condition = (i == 5)) # does not work
result <- result + i * ( x + y)
}
return(result)
}
x <- 2
y <- 3
n <- 10
# debug(fun, condition = (i == 5)) # does not work
debug(fun)
r <- fun(x, y, n)
print(r)
解决方案
if (i == 5) { # inside loop of fun()
browser()
}
正在工作,但我想可能会有更好的选择(函数内没有多余的代码)
is working, but I thougt there might be something better (No extra code inside the function)
推荐答案
您可以在 browser()
中使用参数 expr
:
fun <- function(x, y, n) {
result <- 0
for (i in 1:n) {
browser(expr = {i == 5})
result <- result + i * ( x + y)
}
return(result)
}
如果表达式的计算结果为 TRUE
,则它将仅打开调用 browser()
的环境.
It will then only open the environment where browser()
was called from if the expression evaluates to TRUE
.
如果要使用 debug()
:
debug(fun, condition = i == 5)
然后调用该函数:
fun <- function(x, y, n) {
result <- 0
for (i in 1:n) {
result <- result + i * ( x + y)
}
return(result)
}
fun(x, y, n)
这篇关于如何仅在满足条件时启动调试器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!