musictheory / NilScript

Objective-C-style language superset of JavaScript with a tiny, simple runtime
Other
50 stars 5 forks source link

@each prematurely bails when array has falsy value #89

Closed iccir closed 8 years ago

iccir commented 8 years ago
var sum = 0;
@each (var i in [ 1, 2, 3, 0, 4, 5, 6 ]) {
    sum += i;
}

assert.equal(sum, 21);

facepalm On the bright side, code ported from Obj-C to oj won't usually have a nil in the array.

iccir commented 8 years ago

Generated code:

var sum = 0;
for (var i, $oj_t_2 = ([ 1, 2, 3, 0, 4, 5, 6 ]), $oj_t_0 = 0, $oj_t_1 = ($oj_t_2 ? $oj_t_2.length : 0); ($oj_t_0 < $oj_t_1) && (i = $oj_t_2[$oj_t_0]); $oj_t_0++) {
    sum += i;
}

The issue is the use of && (i = $oj_t_2[$oj_t_0]) to really mean "and execute this regardless".

We want something like: && (i = $oj_t_2[$oj_t_0])|1

iccir commented 8 years ago

Or we can just move the assignment of i into the loop body.