haxegon
haxegon copied to clipboard
Data.create2darray has a subtle bug if used for classes
Hah! Ok, this line:
contents = Data.create2darray(size, size, new DungeonBlock());
...will fill an array with copies of the SAME object. Doh! See if there's anything you can do about that.
the work around for now, of course, is:
contents = Data.create2darray(size, size, null);
for (j in 0 ... size){
for (i in 0 ... size){
contents[i][j] = new DungeonBlock(DungeonBlockType.EMPTY);
}
}
Maybe I can get a macro to do this as intended? Dunno. Might not be possible.
Hey @TerryCavanagh, one way to solve/workaround the issue - without disturbing macros :stuck_out_tongue_winking_eye: - could be to use a function as third parameter, instead of a value: http://try-haxe.mrcdk.com/#6fE4f
@azrafe7, that's interesting! However, I think it's too complex for Haxegon! The purpose of this function is to give people an easy way to construct a blank 2D array of a fixed size, without having to remember how that's done in haxe. (the easiest way is [for (x in 0 ... width) [for (y in 0 ... height) value]], but even that is tricky to internalise!)
Your approach works, but it requires people to remember how to use functions as arguments, which Haxegon doesn't do anywhere else, so it's not really beginner friendly.
Did some poking at this one this morning. This is as far as I got:
@:generic
public static function newcreate2darray<T>(width:Int, height:Int):Array<Array<T>> {
var value:T;
try{
value = cast 0;
}catch (e:Dynamic){
return [for (x in 0 ... width) [for (y in 0 ... height) cast null]];
}
if (Std.is(value, String)){
return [for (x in 0 ... width) [for (y in 0 ... height) cast ""]];
}
return [for (x in 0 ... width) [for (y in 0 ... height) cast null]];
}
The ideal solution is: you can call Data.create2darray(w, h) on any 2d array, and it'll figure out what object it is and default it to null values. If it's an Array<Array<Int>>, you get 0. If it's an Array<Array<String>>, you get "". If it's an Array<Array<Splurg>>, you get null.
The above works on flash, but on html it returns null for everything. It also doesn't work on Dynamic objects.
Here's what I'm currently thinking:
- The only reason
create2darray(w, h, v)even takes that third parameter is because I wanted to be able to create blank arrays. The ideal case for me is a function that creates a 2d array with blank or null cells. - What I want to do is apparently tough! Maybe it's not actually possible?
- Maybe there's a case for a special 2d array class especially for Haxegon? (But does that actually solve the issue, or just create new issues?)
Gonna leave this one a while and talk it over with some Haxe people.