[Maya MEL] Reverse the Order of a Selection List (Natively)

Hi,

I use the command “listRelatives -ad” to return all the children a selected object.
The problem is they are in a reverse order.

For instance, if the hierarchy as follows
grandparent (GP)
parent (P)
 child (C)
  grandchild (GC)

It would return as
GC, C, P, GP

rather than
GP, P, C, GC.

I searched over the web and found some hits. Unfortunately, this one uses a custom script (“zooTools”) that needs installation. http://forums.cgsociety.org/showthread.php?t=190195
I also stumbled upon this native script in this thread (Reversing the order of a string array? - Autodesk Community)
but it does not seem to work and returns the list in the same order.

$selected = `listRelatives -ad `;
for($n=0; $n<size($selected); ++$n) {
$reversed=$selected;
}
print $selected;

Thank you for looking at my problem

Hi bentraje,

I don’t know if there’s a way of doing this in the command, but I wrote my own that does something similar.

proc list_children(string $top_model)
{
    $children = `listRelatives -c $top_model`;
    $size = size($children);
    for($i=0;$i<$size;++$i)
    {
        print $children[$i];
        print "\n";
        list_children($children[$i]);
    }
}

$sel= `ls -sl`;
for ($list in $sel)
{
    list_children($list);
}

Hope this helps!

1 Like

Create a new list > Loop thru the “faulty” list in reverse order and add each item to the new list.

2 Likes

@RiggerRyan

Thanks for the response mate but I get one problem, it also list the shape nodes (which at this moment I don’t need). I tried looking up in the docs but there is no “transform” flag to limit the result to only transform nodes.

Is there a way around this?

@Nightshade

Thanks for the response. But this is my problem, I don’t know how “list in reverse order”. Which is why I am asking the question :frowning:

Simplest way I know, you can just set the value directly to an index in your list. With a little math, you can figure out the proper index.

$selected = `listRelatives -ad`;
string $reversed[];
int $ssel = size($selected);
for($n=0; $n<$ssel; ++$n) {
    $reversed[$ssel - 1 - $n] = $selected[$n];
}
print $reversed;
1 Like

You can pass -type "transform" to both ls and listRelatives, this will filter the results to transform nodes, and their subclasses.
If you need only transform nodes, you’d need to use ls with -exactType "transform"

1 Like

@tfox_TD has the right idea for reversing the list.

If you want to exclude shapes, I’d just look for anything ending “Shape” and exclude it. That’s a quick and dirty way to take care of it anyway :stuck_out_tongue:

1 Like

@TFoxTD @bob.w @RiggerRyan

Slr (I thought it was my internet but it turns out I had problem accessing the site through Google chrome but not in IE).

Thanks for sharing your knowledge. Indeed the “-type “transform”” did the trick.
Also, thanks for sharing this code:
$reversed[$ssel - 1 - $n]

This was new to me.