OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 // Dart test program for testing for statement which captures loop variable. | |
5 | |
6 var f; | |
7 | |
8 main() { | |
9 // Capture the loop variable, ensure we capture the right value. | |
10 for (int i = 0; i < 10; i++) { | |
11 if (i == 7) { | |
12 f = () => "i = $i"; | |
13 } | |
14 } | |
15 Expect.equals("i = 7", f()); | |
16 | |
17 // There is only one instance of k. The captured variable continues | |
18 // to change. | |
19 int k; | |
20 for (k = 0; k < 10; k++) { | |
21 if (k == 7) { | |
22 f = () => "k = $k"; | |
23 } | |
24 } | |
25 Expect.equals("k = 10", f()); | |
26 | |
27 // l gets modified after it's captured. n++ is executed on the | |
28 // newly introduced instance of n (i.e. the instance of the loop | |
29 // iteration after the value is captured). | |
30 for (int n = 0; n < 10; n++) { | |
31 var l = n; | |
32 if (l == 7) { | |
33 f = () => "l = $l, n = $n"; | |
34 } | |
35 l++; | |
36 } | |
37 Expect.equals("l = 8, n = 7", f()); | |
38 | |
39 // Loop variable is incremented in loop body instead of the increment. | |
40 // expression. Thus, the captured value is incremented by one before | |
41 // a new loop variable instance is created. | |
42 for (int i = 0; i < 10; /*nothing*/) { | |
43 if (i == 7) { | |
44 f = () => "i = $i"; | |
45 } | |
46 i++; | |
47 } | |
48 Expect.equals("i = 8", f()); | |
49 | |
50 // Make sure continue still ensures the loop variable is captured correctly. | |
51 for (int i = 0; i < 10; i++) { | |
52 if (i == 7) { | |
53 f = () => "i = $i"; | |
54 } | |
55 continue; | |
56 i++; | |
57 } | |
58 Expect.equals("i = 7", f()); | |
59 | |
60 // Nested loops with captured variables. | |
61 for (int k = 0; k < 5; k++) { | |
62 for (int i = 0; i < 10; i++) { | |
63 if (k == 3 && i == 7) { | |
64 f = () => "k = $k, i = $i"; | |
65 } | |
66 } | |
67 } | |
68 Expect.equals("k = 3, i = 7", f()); | |
69 } | |
OLD | NEW |