Difference between revisions of "Statement Reference"

1,455 bytes added ,  01:11, 3 June 2019
m
no edit summary
imported>Ditre
(not having the conditional values in parenthesis caused undesirable results while testing my own codes)
imported>Teapare
m
 
(3 intermediate revisions by 3 users not shown)
Line 13: Line 13:
<br>
<br>
<source lang="papyrus">
<source lang="papyrus">
; Create a float variable name seconds that starts with a default value
; 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 33: Line 33:
; Assign 5 to x
; Assign 5 to x
x = 5
x = 5
;This assignment is equivalent to x = x + 5
x += 5
;This assignment is equivalent to x = x * (5 + 5)
x *= 5 + 5
</source>
</source>
<br>
<br>
Line 94: 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 111: 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>


Anonymous user