MEL syntax and semantics

Note: text that appears
like this in plain [Courier]
font below represents MEL statements. You can type them into Maya and run them if you like.

Basics:
* free-form
* whitespace - spaces, tabs, blank lines
* scripts are made up of 'procedures' which are made up of 'statements'
* semi-colons terminate statements
* comments - // and /* .. */

 /* this is a comment
    that spans multiple lines */
 // this is a one liner
Variables:
* $..
* global, local
* name globals well, ie meaningfully
* env -lists all global variables currently defined
* run-time determination possible for a newly declared variable, but not while declaring globals/arrays
* arrays - for lists & temporary storage

Data types:
* int
* float
* string
- strings can be concatenated [single strings, NOT string arrays; see below for defn.of arrays]
* vector
* matrix
- can +,-,*,/and % a matrix by a scalar [float or int]
- rows are separated by semicolons, columns by commas
- multiplication of matrices yields a new result matrix
- can negate a matrix
- indices start at 0, not 1
- to access an individual element, say '$f = $m[0][2]`,etc.
* arrays, ordered collections of primitive types [except matrices]
- can grow as needed [dynamic memory allocation]
- size($arrayname)
- clear() to delete
- access: [] to specify an index, eg. '$nextNum = $hugeArray[32];'
- indices start at 0,not 1
* can't add more, int/float/string/vector/matrix are the only available types

 int $i;
 int $j=5;
 int $k, $l;
 int $i = 4.765; // will be truncated (NOT rounded) to 4

 float $f1;
 float $f1a, $f1b;
 float $f2 = 6.65;
 float $f3 = 1/3; // $f3 will be 0, NOT 0.3333333
 float $f4 = 1.0/3; // will be 0.333333333 as expected

 string $a;
 string $fnm = "Saty";
 string $lnm ="Chary";
 string $fullName = $fnm + " " + $lnm; // concatenation; also note the use of a 'spacer' string

 vector $v1 = <<1.0,0.56,-0.96>>;
 print($v1.x); // NEED the ()
 $v1 = <<$v1.x, $v1.y,10.0>>; // NEED to reset all values, can't just set $v1.z [see below]
 $v1.z = 10.0; // NOT allowed, syntax error

 matrix $n[2][2];
 matrix $i2[2][3] = <<1,2,3;-6,.78,.45>>; // 2 rows,3 columns. Note the use of ';' to separate rows
 $j2 = $i2; // $j2 is another matrix created with same contents as $i2 [copied over]
 $k2 = -$i2; // $k2 is a new matrix with values from $i2 NEGATED and copied over

 int $a2[];
 int $b2[100];

 // here's how to initialize an array [specify all values while creating the variable]
 float $flArr[6]= {0.8,-.6,1.,14.,12.3,-7.6};
Operators:
* these symbols ["punctuation", informally speaking] that work with keywords to form statements
* variables assignment: =
* arithmetic: +   -   *   /   %  +=
* Logic: ||   &&   !
* Relational: ==   !=   <   >   <=   >=

Flow control:
* used to express program logic
* grouping
- { } is a block; local vars
* sequential statements
* conditional:
 - if () else if () else..... if () else()
 - switch() case: with break and default
* repetitive:
 - while() {}
- do {} while ()
- for() {}
- for(..in..){}
* sequential statements, conditions and loops can be nested inside each other to create complex ,practical flows of program logic

 string $objs[] = `ls -sl`;
 string $anObj;
 for($anObj in $objs)
 {
  print("Object: " + $anObj + "\n");
 }
Keywords [reserved words]:
* don't use these as variable names in your scripts!
int float string vector matrix
global proc return true false
if else while continue break
for in do switch case
Procedures - the heart of MEL scripting:
* grouping constructs, ie. "building blocks"
* procs talk to each other and with Maya and with the user
* syntax:
[global] proc [return_type] <proc_name> ([args])
{
    [MEL stmts]
}
* think of a proc as a creature with inputs and outputs [sidenote-2D creature]
* when a proc returns something, the returned result is usually captured in a variable
* a global proc stays loaded in memory, even after the script that contains it is all done running
* declaration is not same as execution
* VERY useful to add comments at top & bottom
* namingConvention - run-in words, each word except first has first letter capitalized
* in MEL, graphics 'happen' almost as a side-effect of program execution
* can't 'undo' graphical results of execution
* programs become 'proxies' of the user, since they can be used for modeling, animating, rendering..
* two ways to write a proc that returns the sum of first 'n' digits
 proc doesNothing(){}; // simplest possible MEL procedure
 doesNothing;
 proc makeEllipsoid(float $xs, float $ys, float $zs)
 {
  sphere -p 0 0 0;
  scale $xs $ys $zs;
 }// makeEllipsoid()
 makeEllipsoid 1.0 2.5 0.75;
 makeEllipsoid(1.0,2.5,0.75);

 proc string printAge(int $howOld)
 {
  string $rslt;
  $rslt = "You are " + $howOld + " years old\n";
  return $rslt; // note - we *could* combine all three stmts here into just one [how?!]
 }// printAge()
 printAge(39);// we're ignoring the result
 string $myAge = printAge(36); // we're capturing [storing] the result for later use
Commands, attributes:
* commands are built-in MEL extensions,ie. AW-supplied procs
* these are what make MEL truly useful with Maya,ie they provide CG-related capabilities
* most take extra arguments, ie attribute/value pairs ["what"/"how-much" pairs]
* use either space-separated or () syntax, ie. 'command style' or 'procedure style'
* attributes are the parameters that customize Maya objects
 global proc tstProc(int $a,string $b)
 {
  print ("Hi!\n");
 }// tstProc()
 tstProc 5 "Gnomon"; //ok
 tstProc 5 Gnomon; // also ok [not recommended though]
 tstProc(5,"MEL is neat"); // ok too
 tstProc(5,Hello);// syntax error! *Need* "" inside ()

 vector $v = <<1.,2.,3.>>; 
 $sph = `sphere`; //$sph stores the name [string] of the created sphere 
 setAttr ($sph[0]+".tx") 2.0; // by setting tx, we're translating along X
 setAttr ($sph[0]+".ty") ($v.z); // *need* () to access a vector variable's x or y or z value
 setAttr ("nurbsSphere1.sx") 4.0; // if you know the name of the object for sure
Command execution:
* commands can be executed (run) either using the ` ` or the eval() syntax
* ` ` is useful when you don't have to 'piece together' the command
* eval() is useful when you are concatenating strings and variables to form a command
* commands inside ` ` *must* return something, and that *must* be captured in a variable
* commands inside eval() do not have to return anything and even when they do, there is no need to capture the returned result
 $shape = "cone";
 $cmd = $shape + " -r 5.0";
 eval($cmd);// equivalent to eval($shape + " -r 5.0"); 

 $shape = "sphere";
 $cmd = $shape + " -r 5.0"; // NEED to do this again
 eval($cmd); // note that we're ignoring the return,which would be the name of the created object

 string $xforms[];
 $xforms = `ls -type transform`; // execution using ` `
 $xforms = eval("ls -type transform"); // execution using eval(); note the use of ""

 string $objs[] = `ls -sl`; // fetches the list of selected items

 float $zTran = `getAttr nurbsCone2.tx`; // no need for ""
 $myCone = `cone`;
 float $xTran = `getAttr ($myCone[0]+".tx")`; // NEED the "", since we're piecing together a string
Frequently used built-in commands:

help
ls - lists things
createNode
getAttr
setAttr
connectAttr
listAttr
print
system
env
alias
whatIs - alias/variable/command/plugin/script/none
exists
select
delete
rename
listConnections [DG]
listRelatives [DAG] [eg. xform -> shape]
objectType
objExists
currentTime -
xform - to get and set attrs [at times unintuitive]
error
warning
playbackOptions
group
parent
hide

 help createNode;

 ls;
 ls -sl;
 ls -lights;
 ls -lt;
 ls -type nurbsSurface;

 createNode brush;
 
 alias sph sphere;
 alias delAll {select -all; delete;}; // note TWO ';' at the end

 
 whatIs "sphere";
 whatIs "SelectMenu";
 whatIs "theMeaningOfLife";

 if(`exists createEllipsoid`)
 {
  createEllipsoid 3.0 1.5 4.0;
 }
 else
 {
  print("createEllipsoid not found!\n");
 }

 int $sphExists = `objExists nurbsSphere1`; // 1 if yes, 0 if no

 currentTime 2.0; // to set
 float $currTm = `currentTime -q`; // queries the current (playback) time

 xform -r -ro 0 90 0 -roo zyx;
 xform -q -t -ws nurbsSphere1.cv[2][3];// queries world-space loc of this CV

Built-in mathematical functions:

Script Editor Window, scripts execution: