Skip to content
Prev 359438 / 398502 Next

Persistent state in a function?

On 19/03/2016 12:45 PM, Boris Steipe wrote:
Use local() to create a persistent environment for the function.  For 
example:

f <- local({
   x <- NULL
   function(y) {
     cat("last x was ", x, "\n")
     x <<- y
   }
})

Then:

 > f(3)
last x was
 > f(4)
last x was  3
 > f(12)
last x was  4

Duncan Murdoch