获取功能中的浏览状态 [英] get browsing state in a function
问题描述
我有一个这样的函数:
fun <- function() {
browser()
is_browsing()
}
我想知道 is_browsing的代码是什么()
应该是这样,如果当前正在浏览该函数,则它返回 TRUE
,因此控制台将如下所示:
I would like to know what the code of is_browsing()
should be so it returns TRUE
if the function is currently being browsed, so the console would look like this:
> fun()
Called from: fun()
Browse[1]>
debug at #3: is_browsing()
Browse[2]>
TRUE
但是如果我注释掉 browser()
行,或者按 c
停止浏览, is_browsing()
应该返回 FALSE
,像这样:
However if I comment out the browser()
line, or stop the browsing by pressing c
, is_browsing()
should return FALSE
, like this:
> fun()
Called from: fun()
Browse[1]> c
FALSE
我已阅读有关 debuggingState()
和 isdebugged()
,但在我的情况下它们似乎并没有太大帮助。
I have read about debuggingState()
and isdebugged()
but they don't seem to be of much help in my situation.
FYI的真实案例是在浏览时更新绘图或视图,但仅在浏览时更新(如果我们不这样做,我只想最后绘图/视图一次)以节省资源。
The real case FYI is about updating a plot or view as we browse, but only if we're browsing, if we're not I just want to plot/view once in the end, to spare resources.
推荐答案
使用浏览器时,提示会显示浏览级别:
浏览[1],浏览[2],...
When you use the browser, the prompt shows you the browse level :
Browse[1], Browse[2],...
> browser()
Called from: top level
Browse[1]> browser()
Called from: top level
Browse[2]>
此浏览级别在 main.C
中通过以下方式计算: / p>
This browse level is calculated in main.C
by :
browselevel = countContexts(CTXT_BROWSER, 1);
其中 CTXT_BROWSER
是在 defn.h
:
CTXT_BROWSER = 16
您可以使用此内部 countContexts
函数获取您的 is_browsing
信息重新寻找:
You could use this internal countContexts
function to get the is_browsing
information you're looking for :
is_browsing.cpp
#include <Rcpp.h>
#include <R.h>
#include <Rinternals.h>
using namespace Rcpp;
// [[Rcpp::export]]
int is_browsing() {
return Rf_countContexts(16,1);
}
测试:
library(Rcpp)
sourceCpp('is_browsing.cpp')
test <- function() {
is_browsing()
}
test()
#> [1] 0
browser()
#> Called from: eval(expr, envir, enclos)
test()
#> [1] 1
由 reprex包(v0.3.0)
Created on 2020-08-29 by the reprex package (v0.3.0)
如果在函数内调用浏览器,也可以使用:
Also working if browser is called within function :
test2 <- function() {
browser()
is_browsing()
}
test2()
Called from: test2()
Browse[1]> n
debug à #3 :is_browsing()
Browse[2]> n
[1] 1
如果您希望返回TRUE / FALSE,则Rcpp代码为:
If you wanted a TRUE / FALSE return, the Rcpp code would be:
#include <Rcpp.h>
#include <R.h>
#include <Rinternals.h>
// [[Rcpp::export]]
Rcpp::LogicalVector is_browsing() {
return Rf_countContexts(16,1) > 0;
}
这篇关于获取功能中的浏览状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!