arraysmultidimensional-arrayhaxeneko

Error while assigning array to a row of multidimensional array


I'm writing on Haxe and targeting Neko. Today I've encountered this problem:

var a:Array<Array<Int>> = new Array<Array<Int>>();
a[1] = [1, 2, 3];

The second line throws "Invalid array access" exception. Also it's impossible to iterate on row like this:

for (i in a[0]) ...

A code like that always worked ok, but not the today one. What could be the problem here? The cells and rows I'm trying to access are guaranteed to exist (if talking about indexes).


Solution

  • This issue isn't Neko-specific: = new Array<Array<Int>>() only initializes the outer array - it's equivalent to writing = []. Since it's an empty array, any access will be out of bounds and return null.

    For your particular example, = [[], []] would fix the error (initializes an array with two inner arrays). If you know the number of inner arrays you need beforehand, array comprehension is a convenient way to do the initialization:

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