# Difference between revisions of "Toggling a Variable Between Two Values"

### From GECK

(New page: <p>When toggling a variable between two values, let's call them X and Y, the most obvious method is this:</p> <pre>if VariableName == X set VariableName to Y else set VariableName to X ...) |
|||

Line 14: | Line 14: | ||

<p>A common example of this is toggling a boolean variable - a variable that can only take on the values of 1 and 0:</p> | <p>A common example of this is toggling a boolean variable - a variable that can only take on the values of 1 and 0:</p> | ||

− | + | set sBooleanVariable to 1 - sBooleanVariable | |

If sBooleanVariable is 1, then 1 - sBooleanVariable is 0. Otherwise, if sBooleanVariable is 0, then 1 - sBooleanVariable is 1. As you can see, the above line effectively switches the variable between the two values. | If sBooleanVariable is 1, then 1 - sBooleanVariable is 0. Otherwise, if sBooleanVariable is 0, then 1 - sBooleanVariable is 1. As you can see, the above line effectively switches the variable between the two values. | ||

Keep in mind that, if you use this method, you should make sure that your variable is never set to a value other than the two intended for it (e.g. 1 and 0 in the example above). | Keep in mind that, if you use this method, you should make sure that your variable is never set to a value other than the two intended for it (e.g. 1 and 0 in the example above). | ||

+ | |||

+ | Another method is: | ||

+ | set sBooleanVariable to (sBooleanVariable == 0) | ||

+ | If sBooleanVariable is 1, then (sBooleanVariable == 0) returns 0, setting it to 0, and if sBooleanVariable is 0, then the two are equal, returning 1. |

## Revision as of 20:58, 24 December 2008

When toggling a variable between two values, let's call them X and Y, the most obvious method is this:

if VariableName == X set VariableName to Y else set VariableName to X endif

However, this is not a very efficient method. This is a more efficient method:

set VariableName to (X + Y) - VariableName

A common example of this is toggling a boolean variable - a variable that can only take on the values of 1 and 0:

set sBooleanVariable to 1 - sBooleanVariable

If sBooleanVariable is 1, then 1 - sBooleanVariable is 0. Otherwise, if sBooleanVariable is 0, then 1 - sBooleanVariable is 1. As you can see, the above line effectively switches the variable between the two values.

Keep in mind that, if you use this method, you should make sure that your variable is never set to a value other than the two intended for it (e.g. 1 and 0 in the example above).

Another method is:

set sBooleanVariable to (sBooleanVariable == 0)

If sBooleanVariable is 1, then (sBooleanVariable == 0) returns 0, setting it to 0, and if sBooleanVariable is 0, then the two are equal, returning 1.