6

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).

Gama11
  • 31,714
  • 9
  • 78
  • 100
Gulvan
  • 305
  • 2
  • 12

1 Answers1

8

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) []];
Gama11
  • 31,714
  • 9
  • 78
  • 100
  • Great answer. The "for in an array declaration" trick was unknown to me! Also consider array.insert() as an alternative to assigning values to array positions to help visualize coding when positioning is not that important. I wonder, is declaring the entire content of an array a good practice? Mostly in 2d arrays like this case? – oli_chose123 Apr 30 '18 at 00:00
  • 1
    That's a pretty broad question.. "good practice" in what way? Code style? Performance? etc... Of course for very large arrays it might become problematic, but for "simple cases" I don't see any problem with it. – Gama11 May 01 '18 at 18:09