Seems to me you can get the same results by using an auto-enter of the record number. It will put consecutive number in each row you create. The auto-enter in the portal table would look like this:
Is there some reason you need a script?
The reason I need a script to auto-input because I want to track back this serial to the product. So, I design the serial as product code-year-serial --> SP105-17-001,...002, ,...003 or AC045-17-001... or PD005-17-001.....
See this article for the custom function (requires FMPro Advanced to edit):
Once the serial (incremented) list is created, you can loop the list or use export/import or other methods to get this list into the related records (as you create them).
p.s. there may be a way to fix your script, but it was a little hard for me to read.
Wow! Many thank for your suggestion, Beverly