First of all, the problem you have faced has nothing to do with the scoping. Second, I don't think it is a good idea to call something idiotic just because you don't understand it.
In your example, all functions in a list return the same value because of the lazy evaluation mechanism in R. See help(force)
, which specifically addresses your question. In short, you need to force evaluation of the function at the time you call it, which can be done by adding force
:
functiontest = function() {
foo = list()
for(i in 1:3) {
fixer = function(s) {
force(s) ### <<<---This is the only difference from your code ###
return(
function() {
return(s)
}
)}
foo[[i]] = fixer(i)
}
return(foo)
}
or, using a more concise syntax:
functiontest <- function() lapply(1:3, function(s) {s; function() s})
Example of use:
> L <- functiontest()
> L[[1]]()
[1] 1
> L[[2]]()
[1] 2
> L[[3]]()
[1] 3
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…