TL;DR - The less lines in your code the better, and use argument passing tricks whenever possible. Keep it clean!After talking to a coworker today about how it'd be cool to try and rewrite a script he made in only ten lines of code...I thought it'd be good to to write a short post about how to increase efficiency in your MEL scripting. By efficiency, I mean saving yourself time both in the creation and the editing of your code by condensing your scripts into shorter blocks and not using more lines than you need to. I've found that it helps me a lot in the long term when my scripts are much shorter and easier to edit. On top of that, it's just way more awesome to write a script in ten lines that does the exact same thing as one that does it in fifty.
We'll start with some simple examples:
Let's start with a
FOR Loop. Normally you'd setup a
FOR loop like this:
for($i = 0; $i < 10; $i++) {
print $i ;
}
Or like this..
for($item in $myArray){
print $item ;
}
But why not condense it? Let's put that three lines of code into one.
for($item in $myArray) print $item
It doesn't seem like much of a gain, but in actuality you've cut the size by 66%.
Now let's add an
IF statement to this line..
for($item in $myArray) if($item == "myItem") print $item
Still one line of code but you've got another check in there.
Another example, check if an object exists, error out if not.
int $exists = `objExists $myObject` ;
if(!$exists) {
error "Object doesn't exist." ;
}
// Four lines? Bleh. Let's bring it down a few..
if(!`objExists $myObject`) error "Object doesn't exist." ;
Some more error check examples:
if(!`filetest -f $pathToFile`) error "File does not exist." ;
//
if(!`endsWith $mayaFile ".mb"` && !`endsWith $mayaFile ".ma"`) error "File is not a Maya file." ;
//
This helps a lot when you've got a procedure that has a lot of error checking. Don't allow your checks to steal all of your screen real estate. Condense them into one line and celebrate your awesomeness with a frosty pint.
What about when you need to get some data from a textField or any other control? Assuming it returns a string, and not a string array. You condense the following:
string $myText = `textField -query -text myTextField` ;
print $myText ;
// Pffffff.
print `textField -query -text myTextField` ;
// Much better!
So this is a short, basic look into how to do this sort of stuff. I find that although making your code cleaner and nicer is probably in the top ten nerdiest things possible, you'll appreciate it someday when you look step back and look at your script and actually smile at how cool it looks. It is after all an art form. :)