1

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.

Boris Gorelik
  • 29,945
  • 39
  • 128
  • 170
  • 1
    I think the solution is to not use variables inside the function that you don't pass as arguments. Your function has argument lower case x, but the body evaluates upper case X. Where is upper case X supposed to come from? – Ista Mar 12 '13 at 12:39
  • @Ista, I think that's the point of the question. How to spot such errors which eludes you otherwise (had you declared a X in the global environment by mistake)? – Arun Mar 12 '13 at 12:47
  • @lsta: Arun is right. I have modified the question – Boris Gorelik Mar 12 '13 at 13:03
  • 2
    @bgbg in that case this question is a duplicate of http://stackoverflow.com/questions/6216968/r-force-local-scope and http://stackoverflow.com/questions/3277556/limiting-variable-scope – Ista Mar 12 '13 at 13:41

0 Answers0