I\'m defining functions in a loop and trying to force evaluation of a loop variable without having to carry around a private environment.
Example: a set of functions
Unfortunately base R lacks a function for making functions by hand, but pryr supplies make_function:
library(pryr)
handlers <- list()
for (i in 1:6) {
body <- substitute(message(i), list(i = i))
f <- make_function(alist(), body)
handlers[[paste0('h', i)]] <- f
}
Note the use of substitute to manually modify a quoted call.
Another cool (IMO!) function in pryr is unenclose, which unencloses a function by substituting in the variables defined in the enclosing environment:
msg <- function(i) {
force(i)
function () message(i)
}
msg(1)
# function () message(i)
#
unenclose(msg(1))
# function ()
# message(1)
But their really is no downside to using the original closure.