Skip to content
Prev 328341 / 398498 Next

function closure

Change your 'fileIndex <- fileIndex + 1' to 'fileIndex <<- fileIndex + 1'
so the fileIndex in the environment of the call to generateFiles() is altered
(instead of creating and forgetting about a variable called fileIndex
in the function created by generateFiles.

  generateFiles <- function(path, pattern="\\.xml$") {
      files <- dir(path, pattern=pattern, full.names=TRUE, recursive=TRUE, no..=TRUE)
      total <- length(files)
      fileindex <- 1
      fileGen <- function() {
          if (fileindex < total) {
              fileToReturn <- files[[fileindex]]
              print(fileindex)
              fileindex <<- fileindex + 1
              fileToReturn
          }
      }
      fileGen
  }

used as:

  > nextFile <- generateFiles("c:/temp", pattern="\\.R$")
  > nextFile()
  [1] 1
  [1] "c:/temp/4209/test.R"
  > nextFile()
  [1] 2
  [1] "c:/temp/a.R"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com