get browsing state in a function

前端 未结 4 1590
灰色年华
灰色年华 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:12

    This is not 100% what you are looking for, but perhaps you get an idea how to solve your problem? I am not familiar with C / C++ R-basics, but perhaps you can kind of overload base::browser()?

    I hope this helps:

    list.parent_env <- function() {
      ll <- list()
      n <- 1
      while (!environmentName(.GlobalEnv) %in% 
             environmentName(parent.frame(n))) {
        ll <- c(ll, parent.frame(n))
        n <- n + 1
      }
      return(ll)
    }
    
    listofenv2names <- function(env_list) {
      names <- unlist(lapply(c(1:length(env_list)), function(i) {
        attributes(env_list[[i]])$name
      }))
      return(names)
    }
    
    # https://stackoverflow.com/a/23891089/5784831
    mybrowser <- function() {
      e <- parent.frame()
      attr(e, "name") <- "mybrowser_env"
      assign("mybrowser_env", 1,
             envir = parent.frame(),
             inherits = FALSE, immediate = TRUE)
      return(eval(quote(browser()), parent.frame()))
    }
    
    is_browsing <- function() {
      env_list <- list.parent_env()
      r <- "mybrowser_env" %in% listofenv2names(env_list)
      print(r)
      return(r)
    }
    
    subsubfun <- function() {
      print("subsubfun")
      b <- 2
      is_browsing()
      return(NULL)
    }
    
    subfun <- function() {
      print("subfun")
      a <- 1
      is_browsing()
      subsubfun()
      return(NULL)
    }
    
    fun1 <- function() {
      print("fun1")
      is_browsing()
      mybrowser()
      for (i in 1:10) {
        is_browsing()
      }
      is_browsing()
      subfun()
      
      return(NULL)
    } 
    
    fun2 <- function() {
      print("fun2")
      is_browsing()
      return(NULL)
    }
    
    fun1()
    fun2()
    

    Output looks good:

    [1] "fun1"
    [1] FALSE
    Called from: eval(quote(browser()), parent.frame())
    Browse[1]> c
    [1] TRUE
    [1] "subfun"
    [1] TRUE
    [1] "subsubfun"
    [1] TRUE
    [1] "fun2"
    [1] FALSE
    

提交回复
热议问题