COMMUNITY

Assign break word to a variable

Hej !

I don’t know if it’s a bug of it belongs to “all in haxe is a block” :

class Test {
    static function main() {
        var loop = null;
        do{
            trace( "ok" );
            loop	= break; // compiler lets it because it's inside a loop
        }while( false );
        trace( loop ); // null
    }
}

“Everything is an expression.” I’m pretty sure that the ‘break’ keyword returns a Void type.

2 Likes

Actually, the break skips the assignment altogether. This is even carried down into branches:

class Test {
  static function main() {
    var loop = 4;
    do{
      trace( "ok" );
      loop = if (Math.random() > .5) 5 else break;
    } while( false );
	trace( loop ); // 4 or 5, but never null
  }
}

You can try it here https://try.haxe.org/#c1d42 and take a look at the generated code.

2 Likes

Thanks all four your answer.
I just wonder if compiler should throw an error or if it’s ok like that ?

This works as intended. It’s ok to have a jump (break, continue, return) in a value, e.g.:

class Test {
  static function main() {
    var values = ['foo', 'bar', 'baz', null, 'beep'];
      
    function isFinal(x)
      return x == null;
      
    function shouldSkip(x)
      return x.charAt(0) != 'b';
      
    for (x in values)
      trace(
        if (isFinal(x)) break 
        else if (shouldSkip(x)) continue
        else x
      );
  }
}
1 Like