How to select last n-elements of object

I'm developing an utility which selects last N-elements definied in the Editable_Poly object.

For example (see attachment): Having an object consisting of 6 attached geometries (6 elements as each primitive is one element). The numbers on the picture represent order, in which the other objects were attached to Original object.

1. In the 'left' scenario, objects were attached from left to right, so the last 4 elements are pyramind, torus, cylinder, sphere.
2. In the 'right' scenario objects were attached from right to left, so the last 4 elements are cone, sphere, cylinder, torus.
This is my attempt, but does not work as excepted, as some elements in more complicated situations may have multiple ranges of faces (GetElementsUsingFace returns #{1..10,50..60} for instance so .NumberSet for the bitarray shifts my 'index' incorrectly). The problem is that I'm not able to resolve, how to 'move' to next element.

This however works as expected when each element having just one range #{x..y} (like the example I provided) so .NumberSet shifts my 'index' to next face not belonging to the element.

fn SelectLastNElements n = (
   local numFaces = PolyOp.GetNumFaces $
   local selectionMask = #{} --final face selection  
   local index = numFaces --starting from last face
   for i = 1 to n do (
      local elementMask = PolyOp.GetElementsUsingFace $ index
      index = index - elementMask.NumberSet --this is wrong
      selectionMask = selectionMask + elementMask --add element mask to total face selection
   PolyOp.SetFaceSelection $ selectionMask
   $.ConvertSelection #Face #Element

Is something like this possible?

example.png96.78 KB