Getchildat and type

Hi.

I have no idea why haxe is working this way. I have sprite and it’s childs. and when I get child I can’t use it’s methods becouse it’s displayContainer not my class:

 this.Player.Board.getChildAt(i).lightsDown();

return error:

openfl.display.DisplayObject has no field lightsDown

so I have to cast it:

cast(this.Player.Board.getChildAt(i),Hex).lightsDown();

and it’s working :smile:

but why? Haxe know this is a Hex instance so why I have to cast it?

and he knows becouse when I use this:

 Type.getClass( this.Player.Board.getChildAt(i) ) == Hex

its returning true

It’s not the same,

when you do this.Player.Board.getChildAt(i).lightsDown(); it can be any i
and there’s no way for the compiler to get more informations, who knows what kind of class will be pushed as child.

And when you do Type.getClass( this.Player.Board.getChildAt(i) ) then you are asking the runtime the type of this specific i.

but both are in the same loop. it’s the same i so I don’t really get the difference ;/
is my aproach with cast a good way to do it? or should I do it in some other way?

now I do it like this:

for (i in 0...this.Player.Board.numChildren) {
	if(Type.getClass(this.Player.Board.getChildAt(i)) == Hex)
	    cast(this.Player.Board.getChildAt(i),Hex).lightsDown();
			}

If you know the type already, you could do:

var hex:Hex;
for (i in 0...Player.Board.numChildren) {
	hex = cast Player.Board.getChildAt (i);
	hex.lightsDown ();
}

If you don’t know the type:

var hex:Hex;
var object;
for (i in 0...Player.Board.numChildren) {
	object = Player.Board.getChildAt (i);
	if (Std.is (object, Hex)) {
		hex = cast object;
		hex.lightsDown ();
	}
}

You could also use your own array to keep track of your objects. This is common. Instead of only calling addChild, use tiles.push as well:

public var tiles = new Array<Hex> ();

...

var hex = new Hex ();
Player.Board.addChild (hex);
tiles.push (hex);

...

for (tile in tiles) {
	tile.lightsDown ();
}

By keeping your own list, you keep the objects strongly typed, making it simpler to iterate through, without needing to cast

1 Like

thx !
it is good to know the right way to do it :smile:

but I have question about this one:

why i have to cast twice?

object = cast Player.Board.getChildAt (i);

and

hex = cast object;

also won’t Std.is (object, Hex) work without cast first?

I’m new to haxe, thank You very much for help :slight_smile:

Sorry, I forgot to delete a cast when I copied and modified the original sample.

I meant:

var hex:Hex;
var object;
for (i in 0...Player.Board.numChildren) {
    object = Player.Board.getChildAt (i);
    if (Std.is (object, Hex)) {
        hex = cast object;
        hex.lightsDown ();
    }
}

:slight_smile:

1 Like

…and technically you can do the vars inside the for loops, it’s a bit shorter to read that way, but using one variable can perform better, and prevent a stack overflow in C++ for very large loops