How to initialize all elements of Vector?

On Array I can use comprehension or just to init with

     var testArray : Array<Int> = [ 0x4f727068, 0x65616e42, 0x65686f6c ];

How can achieve same with Vector ? I saw fromArrayCopy and fromData, but both require to have already set variables with Array or VectorData . Any other way ?

var myVector = Vector.fromArrayCopy([0,1,2]);
var anotherOne = Vector.fromArrrayCopy([ for (i in 0...3) i ]);

The downside is that the array literal is converted to an array before Vector gets hold of it, so it’s a tiny bit inefficient. However, the objects of the array aren’t duplicated, only the pointers.

You can use a macro for that: http://try-haxe.mrcdk.com/#CC1ae

Macro.hx:

import haxe.macro.Expr;

class Macro {
  public static macro function initVector(expr:Array<Expr>) {
    return macro {
      var vec = new haxe.ds.Vector($v{expr.length});
      $b{[for(i in 0...expr.length) macro vec.set($v{i}, ${expr[i]})]}
      vec;
    }
  }
}

and use with:

var vec = Macro.initVector(1, 2, 4, 5, 6);
trace($type(vec));
2 Likes