TWiki
> Main
>
BooleanVariables
True/False Variables
This is a specialised variable that can be thought of as a switch. It has only two states: true or false (on or off). It is of course possible to store equivalent information in either a text or number variable, but it is recommended that when appropriate a true/false variable is used for the following reasons:
- it is more efficient in terms of memory usage
- it is less prone to error (see below)
- it allows shortcuts to be used when testing its value
Note that this type of variable is more commonly referred to as a Boolean.
Creating a true/false variable
Right click on State and select 'Add True False'.
In the properties change the name to something meaningful (i.e. something that describes what the variable will store like 'introComplete', or 'gameOver'). You can also set a default value for the variable.
Setting the value with code
Setting the value of a true/false variable in code is straightforward. In fact there are only two possible options:
myTrueFalseVariable.Value = true;
myTrueFalseVariable.Value = false;
You start with the name of your text variable, add a full stop - at which point a pop-up should appear - add 'Value', then an equals sign. You then set the variable to either
true or
false. Note the absence of inverted commas. The value being stored in mscape is
not text, but one of two states understood by mscape.
If you happen to make a typo in the state name mscape will display an error message when you save or test your mscape. If you had chosen to use a text variable to store a true/false state you would receive no such warning in the case of a typo and your mscape might fail with no indication of where the problem lies. Note also that
true and
false appear blue in the code editor since they are recognised
keywords.
Accessing the value of a text variable
Simply reference the Value property of the variable. The most likely reason to want to access a true/false variable is to test its value with a condition. In this case there are some handy shortcuts.
The usual long-hand methods of testing the state of true/false variables are as follows:
To test if the value is true:
if (myTrueFalseVariable.Value == true) {
// do this...
}
To test if the value is false:
if (myTrueFalseVariable.Value == false) {
// do this...
}
However to test whether a true/false variable is
true you may omit the "== true" from the condition:
if (myTrueFalseVariable.Value) {
// do this...
}
There is also a shortcut method to test if a value is false by using the NOT operator (an exclamation mark: !), placing it in front of the variable reference as follows:
if (!myTrueFalseVariable.Value) {
// do this...
}
Effectively we're saying "if NOT myTrueFaleVariable" (i.e. it is
false) then do the following.