get_globals: Get global variables on a function

View source: R/get_globals.R

get_globalsR Documentation

Get global variables on a function

Description

Get global variables on a function

Usage

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)

## 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)


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

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()

HenrikBengtsson/environments documentation built on Jan. 15, 2025, 12:58 a.m.