GNOME Bugzilla – Bug 672767
Local variable from foreach block does not get assigned for closure
Last modified: 2012-03-24 20:48:38 UTC
Hello, in this code: class ClosureBug: GLib.Object { class TestClass { public int test = 42; } delegate int ReturnTestClass(); TestClass[] tests = new TestClass[2]; public void do_test() { tests[0] = new TestClass(); tests[1] = new TestClass(); ReturnTestClass rtc = null; foreach (TestClass tc in tests) { rtc = () => { return tc.test; }; } GLib.stdout.printf("This should be 42: %d\n", rtc()); } public static int main(string[] args) { ClosureBug cb = new ClosureBug(); cb.do_test(); return 0; } } Vala generates an error: /tmp/closure-test1.vala.PH3CBW.c: In function ‘closure_bug_do_test’: /tmp/closure-test1.vala.PH3CBW.c:198:4: error: ‘tc’ undeclared (first use in this function) It seems the generator prepares the closure structure correctly (from the generated code): struct _Block1Data { int _ref_count_; ClosureBug * self; ClosureBugTestClass* tc; }; But for some reason it cannot use it.
*** This bug has been marked as a duplicate of bug 628336 ***
Thanks Luca. The workaround is to use Gee arrays.