get browsing state in a function

前端 未结 4 1615
灰色年华
灰色年华 2021-02-13 20:30

I have a function such as this one :

fun <- function() {
  browser()
  is_browsing()
} 

I would like to know what the code of is_browsin

4条回答
  •  面向向阳花
    2021-02-13 21:33

    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]> 
    

    This browse level is calculated in main.C by :

    browselevel = countContexts(CTXT_BROWSER, 1);
    

    Where CTXT_BROWSER is a constant defined in defn.h:

    CTXT_BROWSER  = 16
    

    You could use this internal countContexts function to get the is_browsing information you're looking for :

    is_browsing.cpp

    #include 
    #include 
    #include 
    using namespace Rcpp;
    
    
    // [[Rcpp::export]]
    int is_browsing() {
      return Rf_countContexts(16,1);
    }
    

    Test :

    library(Rcpp)
    sourceCpp('is_browsing.cpp')
    test <- function() {
      is_browsing()
    }
    
    test()
    #> [1] 0
    
    browser()
    #> Called from: eval(expr, envir, enclos)
    
    test()
    #> [1] 1
    

    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
    

    If you wanted a TRUE / FALSE return, the Rcpp code would be:

    #include 
    #include 
    #include 
    
    // [[Rcpp::export]]
    Rcpp::LogicalVector is_browsing() { 
      return Rf_countContexts(16,1) > 0;
    }
    

提交回复
热议问题