Skip to content
Prev 177249 / 398513 Next

static variable?

On 4/16/2009 8:46 AM, ivo welch wrote:
You put such things in the environment of the function.  If you don't 
want them to be globals, then you create the function with a special 
environment.  There are two common ways to do this:  a function that 
constructs your function (in which case all locals in the constructor 
act like static variables for the constructed function), or using 
local() to construct the function.

For example

 > makef <- function(x) {
+    count <- 0
+    function(y) {
+       count <<- count + 1
+       cat("Called ", count, "times\n")
+       y + x
+    }
+ }
 >
 > add3 <- makef(3)
 >
 > add3(4)
Called  1 times
[1] 7
 > add3(6)
Called  2 times
[1] 9
That's exactly what <<- is designed for, so you'd have to use some 
equivalent with assign() to avoid it.

Duncan Murdoch