Get global variables on a function

get_globals(fcn, must_exist = FALSE)

Arguments

fcn

The function.

must_exist

If TRUE, an error is produced if one of the prospect globals cannot be located.

Value

A named list of globals.

Examples

## Here 'a' is a global variable
a <- 42
f <- function() pi * a
globals <- get_globals(f)
utils::ls.str(globals)
#> a :  num 42

## Here 'a' is not a global variable, because it is part of
## the environment of 'f', which is a local environment
## that comes with function 'f'
f <- local({
  a <- 42
  function() pi * a
})
globals <- get_globals(f)
utils::ls.str(globals)
#> a :  num 42


## Same here; 'a' is not a global variable
f <- local({
  a <- 42
  local({
    function() pi * a
  })
})
globals <- get_globals(f)
utils::ls.str(globals)
#> a :  num 42

my_fcn <- function(prune = FALSE) {
  huge <- rnorm(1e6)
  
  n <- 2
  
  g <- local({
    pi <- 3.14
    function() n * pi
  })

  globals <- globals::globalsOf(g, envir = environment(g), mustExist = FALSE)
  str(globals)
  globals <- globals::cleanup(globals)
  str(globals)
  fcn_globals <- get_globals(g)
  str(fcn_globals)
}


my_fcn()
#> List of 3
#>  $ * :function (e1, e2)  
#>  $ n : num 2
#>  $ pi: num 3.14
#>  - attr(*, "where")=List of 3
#>   ..$ * :<environment: base> 
#>   ..$ n :<environment: 0x55f418357418> 
#>   ..$ pi:<environment: 0x55f418359f40> 
#>  - attr(*, "class")= chr [1:2] "Globals" "list"
#> List of 2
#>  $ n : num 2
#>  $ pi: num 3.14
#>  - attr(*, "where")=List of 2
#>   ..$ n :<environment: 0x55f418357418> 
#>   ..$ pi:<environment: 0x55f418359f40> 
#>  - attr(*, "class")= chr [1:2] "Globals" "list"
#> List of 2
#>  $ n : num 2
#>  $ pi: num 3.14
#>  - attr(*, "where")=List of 2
#>   ..$ n :<environment: 0x55f418357418> 
#>   ..$ pi:<environment: 0x55f418359f40> 
#>  - attr(*, "class")= chr [1:2] "Globals" "list"