How to isolate a function

How can I guarantee that when calling a function, it is not allowed to capture variables from the global environment?

I want the following code to give me an error. The reason is that I could be wrong z (I wanted to type y).

z <- 10 temp <- function(x,y) { y <- y + 2 return(x+z) } > temp(2,1) [1] 12 

I guess the answer is related to the environments, but I haven't figured them out yet.

Is there a way to make my desired default behavior (e.g. by setting a parameter)?

+6
source share
3 answers
 > library(codetools) > checkUsage(temp) <anonymous>: no visible binding for global variable 'z' 

The function does not change, so there is no need to check it every time it is used. findGlobals is more general and a bit more cryptic. Sort of

 Filter(Negate(is.null), eapply(.GlobalEnv, function(elt) { if (is.function(elt)) findGlobals(elt) })) 

can visit all the functions in the environment, but if there are several functions, maybe it's time to think about writing a package (this is not so difficult).

+4
source
 environment(temp) = baseenv() 

See also http://cran.r-project.org/doc/manuals/R-lang.html#Scope-of-variables and ?environment .

+5
source
 environment(fun) = parent.env(environment(fun)) 

(I use "fun" instead of your temp function name for clarity)

This will remove the workspace environment (.GlobalEnv) from the search path and leave everything else (for example, all packages).

+1
source

Source: https://habr.com/ru/post/900578/


All Articles