Use codetools::findGlobals()
and codetools::findLocalsList()
to find
global and local variables in a piece of code. Global variables are defined
outside the code, and local variables are created inside the code.
find_globals(code, envir = parent.frame())
find_locals(code)
A character vector of the variable names. If the source code contains syntax errors, an empty character vector will be returned.
Due to the flexibility of creating and getting variables in R, these
functions are not guaranteed to find all possible variables in the code
(e.g., when the code is hidden behind eval()
).
x = 2
xfun::find_globals("y = x + 1")
#> [1] "x"
xfun::find_globals("y = get('x') + 1") # x is not recognized
#> character(0)
xfun::find_globals("y = zzz + 1") # zzz doesn't exist
#> character(0)
xfun::find_locals("y = x + 1")
#> [1] "y"
xfun::find_locals("assign('y', x + 1)") # it works
#> [1] "y"
xfun::find_locals("assign('y', x + 1, new.env())") # still smart
#> character(0)
xfun::find_locals("eval(parse(text = 'y = x + 1'))") # no way
#> character(0)