Difference between revisions of "Statement Reference"
Discovered a major foot-gun related to While loops and variable lifetime. Documenting it here.
imported>CT m (→Examples) |
imported>Chesko (Discovered a major foot-gun related to While loops and variable lifetime. Documenting it here.) |
||
Line 117: | Line 117: | ||
x += 1 | x += 1 | ||
endWhile | endWhile | ||
</source> | |||
=== While and Variable Lifetime === | |||
Variables defined inside While loops have a lifetime of as many times as the loop runs, not a lifetime of each iteration of the loop as one might expect. This means that it is very important to always assign a value to variables defined inside a While loop, or avoid defining variables inside While loops altogether. | |||
Here is an example to illustrate this potential pitfall. | |||
<source lang="papyrus"> | |||
int i = 0 | |||
while i < 5 | |||
int j | |||
j += 1 | |||
debug.trace("j = " + j) | |||
endWhile | |||
</source> | |||
Here, j is defined inside the loop. Since we are calling "int j" each iteration, and since the default value of an integer is 0, we might expect output that resembles: | |||
<source lang="papyrus"> | |||
[06/04/2016 - 01:24:38PM] j = 1 | |||
[06/04/2016 - 01:24:38PM] j = 1 | |||
[06/04/2016 - 01:24:38PM] j = 1 | |||
[06/04/2016 - 01:24:38PM] j = 1 | |||
[06/04/2016 - 01:24:38PM] j = 1 | |||
</source> | |||
However, since j's value is maintained across iterations of the loop, we instead get: | |||
<source lang="papyrus"> | |||
[06/04/2016 - 01:49:52PM] j = 1 | |||
[06/04/2016 - 01:49:52PM] j = 2 | |||
[06/04/2016 - 01:49:52PM] j = 3 | |||
[06/04/2016 - 01:49:52PM] j = 4 | |||
[06/04/2016 - 01:49:52PM] j = 5 | |||
</source> | </source> | ||