MEL Tip 005: Toggle Booleans

In this video I explain what a boolean data type is and how to easily toggle them on or off.

A boolean is a data type that represents two different states. Those states could be true/false, on/off, yes/no, or one/zero.

In MEL we don’t have an actual data type called boolean, but instead we use the integer data type to represent them.

int $boolean = true;

$boolean = (!$boolean);
print $boolean;
// 0 will now print since the number zero represents false

In the above code we have an integer named $boolean and we’re assigning it to be true. The words true and false are keywords in MEL and they’re the equivalent to one and zero, so the following all mean the same thing:

int $boolean = true;    is the same as   int $boolean = 1;

int $boolean = false;    is the same as   int $boolean = 0;

Once line 3 is executed the $boolean variable will now equal false.

When you read line 3 you can think of the exclamation point as representing the word not. On line 1 we assign the $boolean variable to equal true, so when you read line 3 you can say $boolean is equal to not true, which in turn makes it false, because if something is not true then it must be false.

If the $boolean variable were false and we execute line 3 then the $boolean variable will equal true because if it’s not false then it must be true.

int $boolean = false;

$boolean = (!$boolean);
print $boolean;
// 1 will now print since the number one represents true


Here are a couple of practical examples using this technique. In this first example is a script that will toggle the Isolate Select on or off.

string $panel = `getPanel -withFocus`;

int $isolateState = `isolateSelect -q -state $panel`;

enableIsolateSelect $panel (!$isolateState);


And this example shows how you can use the technique to toggle the -lock flag on each of the attributes in the Channel Box:

string $objects[] = `ls -sl`;

for ($object in $objects)
    string $keyableAttrs[] = `listAttr -keyable $object`;
    for ($keyableAttr in $keyableAttrs)
        string $objectAttr = ($object + "." + $keyableAttr);
        int $lock = `getAttr -lock $objectAttr`;
        setAttr -lock (!$lock) $objectAttr;

Toggling boolean data types is a technique you can basically use in any of the programming languages you may learn in the future, so it’s a useful thing to know!

Key Takeaways

1. Using an exclamation point in front of a boolean variable will toggle it to the opposite state.

2. getPanel -withFocus will tell you which panel currently has focus.

3. Using enableIsolateSelect $panel $isolateState will allow you to turn on/off Isolate Select.

4. listAttr -keyable $object will return a list of all the keyable attributes within the Channel Box.

One comment

  1. […] learn more about Scripting a Boolean Toggle in Maya, check Greg’s site here, where he provides the code, plus some practical […]

Leave a Reply

Your email address will not be published. Required fields are marked *