18,700
edits
(improving instructions on function calling; correcting "some_function" to "prepare_fight") |
(→if: the previous fix of using a setter function was not only unneeded, but bare bool references do not work in Windows; recommending global variable instead) |
||
Line 169: | Line 169: | ||
That indentation on "spawn_considered" is misleading; when glancing at this code, you might expect that "spawn_considered" only is changed if "a" is greater than zero. It could be the script's writer really did want that line to be subject to the "if" statement, but he forgot to add braces. Always using braces around an "if" statement's body, even when it's one line long, will prevent that mistake. | That indentation on "spawn_considered" is misleading; when glancing at this code, you might expect that "spawn_considered" only is changed if "a" is greater than zero. It could be the script's writer really did want that line to be subject to the "if" statement, but he forgot to add braces. Always using braces around an "if" statement's body, even when it's one line long, will prevent that mistake. | ||
Unfortunately | Unfortunately, even ''with'' braces, BSL does not always respect scope for blocks of code under "if" statements; for instance, a "return" statement will fire even when the surrounding "if" condition is false (see [[#Flow interrupt|Flow interrupt]] for an example). An even more alarming example of bad scoping is this: | ||
func void broken_if(void) | func void broken_if(void) | ||
Line 180: | Line 180: | ||
one_equals_two = true; # ...this will still run | one_equals_two = true; # ...this will still run | ||
if (one_equals_two) | if (one_equals_two eq true) | ||
dprint("Uh-oh."); | dprint("Uh-oh."); | ||
else | else | ||
Line 186: | Line 186: | ||
} | } | ||
Bungie West was aware of this bug, and | Bungie West was aware of this bug, and avoided it by never setting variables under "if" statements. However, you can safely do so as long as you use a global variable. For some reason, assigning a global variable under an "if" will not fire out of scope: | ||
var bool one_equals_two; | var bool one_equals_two = false; | ||
func void fixed_if(void) | func void fixed_if(void) | ||
Line 194: | Line 194: | ||
var int one = 1; | var int one = 1; | ||
var int two = 2; | var int two = 2; | ||
if (one eq two) | if (one eq two) | ||
one_equals_two = true; | |||
if (one_equals_two | if (one_equals_two eq true) | ||
dprint("Uh-oh."); | dprint("Uh-oh."); | ||
else | else | ||
Line 237: | Line 211: | ||
} | } | ||
Another unused feature of BSL is that you can express the opposite of some condition by using the "!" operator (pronounced "not"). The following two statements have the same meaning: | |||
if (!one_equals_two) | if (!(one_equals_two eq true)) | ||
if (one_equals_two eq false) | if (one_equals_two eq false) | ||
====else==== | ====else==== |