- Code: Select all
foreach(var i; var mode = [1,2,3])
setlistener("foo["~i~"]", func() {
print("mode =", i);
});
The callback (func expression) will only be evaluated once the listener is triggered - at that point, external variables, like "i", will be 3.
Thus, you need to capture such variables in a closure, i.e. by using a generator function or an anonymous function.
- Code: Select all
foreach(var i; var mode = [1,2,3])
(func { # creates an anonymous function
var n = i;
setlistener("foo["~n~"]", func() {
print("mode =", n);
}); # end of setlistener
}) # end of anonymous function
(); # directly calls the anonymous function