Skip to content

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

Open

Description

@faerot

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)

Activity

  1. AlexECX commented on Apr 25, 2019

    @AlexECX

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

  2. faerot commented on May 11, 2019

    @faerot
    Author

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

  3. AlexECX commented on May 12, 2019

    @AlexECX

    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.

  4. faerot commented on May 12, 2019

    @faerot
    Author

    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.

  5. AlexECX commented on May 12, 2019

    @AlexECX

    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.

  6. faerot commented on May 14, 2019

    @faerot
    Author

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

  7. faerot commented on Jun 10, 2019

    @faerot
    Author

    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

  8. AlexECX commented on Jun 18, 2019

    @AlexECX
    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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions