Difference between revisions of "Statement Reference"
m
no edit summary
imported>CT m (→Examples) |
imported>Teapare m |
||
(2 intermediate revisions by 2 users not shown) | |||
Line 13: | Line 13: | ||
<br> | <br> | ||
<source lang="papyrus"> | <source lang="papyrus"> | ||
; Create a float variable | ; Create a float variable named seconds that starts with a default value | ||
float seconds = CurrentTimeInMinutes() * 60.0f | float seconds = CurrentTimeInMinutes() * 60.0f | ||
</source> | </source> | ||
Line 100: | Line 100: | ||
x = 0 | x = 0 | ||
endIf | endIf | ||
</source> | |||
<br> | |||
<source lang="papyrus"> | |||
; if the sum of x and y is less than 10, set z to 1, otherwise set z to -1. | |||
if ((x + y) < 10) | |||
z = 1 | |||
else | |||
z = -1 | |||
endif | |||
</source> | </source> | ||
Line 117: | Line 126: | ||
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> | ||