variable declaration reset
- Posted by petelomax Apr 15, 2022
- 1106 views
This just surprised me:
sequence s = {1,2,2,3,4,4,5} for i=1 to length(s) do integer curr = s[i], prev if i>1 and curr=prev then ?{i,s[i]} end if prev = curr end for
On desktop/Phix you get {3,2} and {6,4}, but under pwa/p2js you get precisely nuttin.
JavaScript actually resets prev at the start of every iteration, whereas desktop/Phix leaves it be.
One fix is to simply move the declaration of prev outside of|above the loop, and then they match.
Another way to fix it is to replace "let" in the JavaScript with "var", which triggers legacy hoisting...
[However a blanket use of "var" would fail badly in say "if cond then atom a ... else atom a" cases]
I'm intrigued to know how (various versions of) Euphoria handle this,
and whether to do the same on desktop/Phix and risk breaking legacy code,
or not do that, but somehow (and that's the question) issue a warning/error.
I've also created a rosettacode task to see what that yields.