rener172846
rener172846

Reputation: 451

Haxe - How to initialize all members of an array to the same value?

I need to initialize an array with given size and same value.
For example, create an array of int that has size 10 and set all values to 0.

Int[] array = new Int[10]{0}

In other languages it's very easy, but I'm not sure how to solve this problem on Haxe.
Please help me.

Upvotes: 1

Views: 249

Answers (2)

Justinfront
Justinfront

Reputation: 472

I would not use the word 'array' since Array is reserved and it's confusing, often I use 'arr' instead. No need to type it, that is inferred so it's bit cleaner and lighter:

var arr = [for (i in 0...10) 0];

A macro approach would put the result in the compiled code which would run faster.

var arr = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];

and is explained here:

https://code.haxe.org/category/macros/build-arrays.html

Upvotes: 0

Andrew
Andrew

Reputation: 1292

You could use Array Comprehension

var array:Array<Int> = [for (i in 0...10) 0];

Upvotes: 3

Related Questions