10.7 Fundamentals - Stateful functions
Because
- The enclosing environment is unique and constant, and
- We have
<<-
(super assignment)
We can change that enclosing environment and keep track of that state across iterations (!)
<-
Assignment in current environment<<-
Assignment in parent environment
new_counter <- function() {
i <- 0
function() {
i <<- i + 1 # second assignment (super assignment)
i
}
}
counter_one <- new_counter()
counter_two <- new_counter()
c(counter_one(), counter_one(), counter_one())
#> [1] 1 2 3
c(counter_two(), counter_two(), counter_two())
#> [1] 1 2 3
“As soon as your function starts managing the state of multiple variables, it’s better to switch to R6”