It can be tricky keeping track of things through zscript. The way you’re doing it is basically the best way. I’m not sure what circumstances cause the re-ordering you describe. I’m afraid the only way of sorting that out would be to be clear of when it happens and then adjust the code accordingly. However, make sure that you are actually seeing a change in the order - for some operations (such as cloning) ZBrush will rename the original tool/subtool. This can be confusing!
Here are a few of other things that might help:
You can use [ToolGetCount] to find out how many tools there are in the Tool Palette. As they are numbered starting at 0, one less than the total will be the last in the list.
Each subtool has an ID that can be got using [SubToolGetID]. This can help identify the Tool (if you have the top subtool selected) though be warned: the ID is not unique - duplicated or cloned subtools will have the same ID.
Names can be a useful way of tracking what’s happening. You can use [ToolGetPath] to get the full path for any tool in the Tool palette without selecting it. So [ToolGetPath,49] would give you the path for the tool at position 49 (the 50th tool). You can then use [FileNameExract] to get just the name:
Then you could compare it with a stored name:
[If,(([Strlength, toolName] == [Strlength, myStr] )&&([StrFind,myStr,toolName]==0)),
//the tool is called “Dog”
Checking the string length makes sure the strings are the same. Without it - just using StrFind - you could look for names that contain the stored string, such as “Dog_Merged” etc.