For-To-Next flaw in conversion to Javascript

Hi

The issue arises when/if I code something like:

For i=a To b Step c
    ...
Next

This gets translated to

for (i = (a); i <= b; i += c) {
    if ((i) < (b) && (c) < 0) break;
    ...
}

which looks fine at first glance, but if, say,

a=1
b=-5
c=-2

then it doesn’t even loop through once, because the condition should now be i>=b instead of i<=b.

To fix this, how about changing the Javascript to something like:

i = a - c;
for (NSBtemp = 0; NSBtemp <= Math.trunc((b - a) / c); NSBtemp++) {
    i += c;
    ...
}

That would work every time (I believe!).

You can also then add an extra check by adding something like the following:

if (((b - a) / c) < 0) {
    break;   // Loop going the wrong way
}

Food for thought? :man_shrugging: :smiley:

Thanks. We’ve opened an issue for this. It won’t be fixed immediately, so best bet is to make a workaround.

Thanks for the detailed analysis and potential fix!

Glad I could help.

Just to add that I’ve since established that it’s Math.floor you need to use and not Math.trunc. :slight_smile:

Thanks.

Thanks - noted.