I figure after your initial line (Loop) you should set the variable to a value of 0. That way whenever the outer loop is executing it sets the value and the the inner loop set it to value+1 etc. make sure you set a condition to exit each loop.
In other words:
Set Variable [$K ; value: 0 ]
Set Variable ($K; $K + 1)
I was explaining the idea but should have taken the time to write the code.
Thanks Rick and PhilModJunk!
I lost a long time figuring out why my script did not work as expected and could then not figure out a valuable solution.
But during the night, I came to the same solution as you and indeed, that makes the trick ;-)