Skip to content

for i in range(a, b, c) is not translated to for (;;) loop #625

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
faerot opened this issue Mar 22, 2019 · 8 comments
Open

for i in range(a, b, c) is not translated to for (;;) loop #625

faerot opened this issue Mar 22, 2019 · 8 comments

Comments

@faerot
Copy link

faerot commented Mar 22, 2019

If range has extra arguments, it treats for loop like a loop over regular sequence.
It should be fairly trivial to make
for i in range(begin, end, step)
to translate into
for (i=begin; i < end; i += step)

@AlexECX
Copy link

AlexECX commented Apr 25, 2019

Just tried it and it's working, for i in range(0, 5, 2) gives for (var i = 0; i < 5; i += 2).

@faerot
Copy link
Author

faerot commented May 11, 2019

Maybe it is working for constants, try using variables as arguments to see the bug.

@AlexECX
Copy link

AlexECX commented May 12, 2019

After looking at the js source, my guess would be that the transpiler cannot know at compile time whether or not var step(edited) is positive or negative, so it can't decide which of i < end; and i > end; is the right code. This is taken care of at runtime by the range function.

@faerot
Copy link
Author

faerot commented May 12, 2019

maybe using != instead of < or > would solve the issue when step is not given or constant 1 or -1? using range() is a major overhead since it generates array every time. Don't want to resort to using while as it hurts readability.

@AlexECX
Copy link

AlexECX commented May 12, 2019

Based on the range() function implementation, perhaps this could do:

for (var i = begin; step > 0 ? i < end : i > end; i += step){
    //stuff
}

It's about <1.5x slower than directly writing it in javascript, but orders of magnitude faster than the current implementation.

@faerot
Copy link
Author

faerot commented May 14, 2019

indeed, looks like a great solution for what it's worth

@faerot
Copy link
Author

faerot commented Jun 10, 2019

Another gotcha in the for loop:
in python the loop for i in range(10): assigns value to i each iteration so in the iteration you can modify it without fear. In transcrypt if it is unrolled into for (i = 0; i < 10; ++i) this will break the code if you will try to modify i within iteration.

Suggested solution - use temporary variable for looping and assign it to i each iteration

@AlexECX
Copy link

AlexECX commented Jun 18, 2019

for i in range(0,2):
    i = i + 2

Already gives

for (var i = 0; i < 2; i++) {
    var i = i + 2;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants