Here's a situation I have a file that defines functions, let's call it tmpFunctions.R
and a file that uses it (let's call it tmpRunner.R
).
A function in tmpFunctions.R
makes an unintentional use of a variable that was never defined in it, but that was defined in the global scope in tmpRunner.R
. Since, at the time the function is called from tmpRunner.R
, the variable already exists in the global score, the interpreter does not issue any error and the program runs smoothly, but to produces wrong results.
Here's an example:
tmpFuncitons.R:
my.func <- function(x){
return(X * 2) # typo; should be error
}
tmpRunner.R
source('tmpFunctions.R')
X <- 10 #calling my.func(...) from this point on will not cause runtime errors
for(i in seq(10)){
print(sprintf('%s ==> %s', i, my.func(i)))
}
output:
> source('C:/tmp/tmpRunner.R')
[1] "1 ==> 20"
[1] "2 ==> 20"
[1] "3 ==> 20"
[1] "4 ==> 20"
[1] "5 ==> 20"
[1] "6 ==> 20"
[1] "7 ==> 20"
[1] "8 ==> 20"
[1] "9 ==> 20"
[1] "10 ==> 20"
Is there a way to either prevent this by something similar to Perl's use strict
, to import the functions in tmpFunctions.R
without exposing them to the global scope (most probably not)?
I also tried to look for source code static analysis tools for R (to get warning messages before running the code), but couldn't find nothing.