LiveScript
LiveScript copied to clipboard
i = 5; for i to 10... # iterates from 0 to 10
When making a [for] expression like:
x = []
i = 5
for i to 10
x.push i
x
We get iterations from 0 to 10, but not from 5 to 10. Sometimes, it happens that [i] has already been set so this kind of code will not produce the expected result. It might be better to leave variable as it appear in cycle and not to add implicit [from 0]. If you feel the same or have any suggestions, please let me know.
x = []
i = 5
while i <= 10, i++
x.push i
x
summivox,
Yes, this does the job, but the topic is not really about the job.
but the topic is not really about the job
I understand your intent. However, keep in mind that for
in LSC has "foreach" semantics (i.e. iterator loop) which has the following implications:
- loop var binding is local to loop scope
- loop var binding is immutable (i.e. you should never assign / op-assign to it)
These are, unfortunately, not enforced in LSC as it compiles to ES5 function-scope var
, while ES6 people can simply do for (const i = ... ; ... ; ...) { ... }
, where i
becomes local to the loop scope and immutable. There is for let
in LSC and I encourage you to explore it.
There is one enforced rule in LSC though:
- each expression in
for
loop head is evaluated once and only once
So you can do this instead:
i = 5
for i from i to 10
i
Of course there is always the escape-hatch: A C-style "for" in LSC is canonically implemented using the "hidden" syntax while cond-expr, incr-expr
I just showed.
Thanks for your feedback. You are fully correct about object iterator (foreach). If we think in terms of LSC, it's easy to distinct object iterator and simple integer - it's [ of ] for object and [ to/in ] for integer. So, when switching to integer, it's a question of implicit:
[from i] VS [from 0]
..in LSC [for i to j] expression. Im not a big expert in LSC and new ES standards, so you have to be right about immutable for, but I felt that this small change would produce cleaner code.
but I felt that this small change would produce cleaner code.
in a backwards-incompatible way
in a backwards-incompatible way
..for those, who relied on implicit [from 0].
I (and I think am not the only one) very often rely on implicit from 0
.
i bet, that's because you more bound to array enumerations.
for a,b in array
is cleaner than for b to array.length - 1
No, for arrays I always use for..in
. for i til n
is an easy way to iterate n times.