Open utterances-bot opened 5 years ago
Very useful for converting a nodelist to an array in one line.
arr:Array<Element> = [for (n in nodelist) cast(n, Element)]
How do you perform array equality checks? I've got a super simple use case of:
public function update(dt: Float) {
var movementVector: Array<Int> = [0, 0];
if (hxd.Key.isDown(hxd.Key.UP)) {
movementVector = [0, -1];
}
if (hxd.Key.isDown(hxd.Key.DOWN)) {
movementVector = [0, 1];
}
if (hxd.Key.isDown(hxd.Key.LEFT)) {
movementVector = [-1, 0];
}
if (hxd.Key.isDown(hxd.Key.RIGHT)) {
movementVector = [1, 0];
}
if (movementVector != [0, 0]) { // This equality check is always False. There's nothing whatsoever in the docs about checking the equality of an array.
// Do stuff here
}
@joereynolds There is no standard library method for equality checking of arrays (there is no way to define value types in Haxe in general for now). You can define your type as an abstract, then overload the equality operator. You can also write a generic array-equality function and use it as a static extension.
@joereynolds not really an answer to your question, but I would rewrite your example like this:
public function update(dt: Float) {
var movementVector: Array<Int> = [0, 0];
var isMoving = true;
if (hxd.Key.isDown(hxd.Key.UP)) {
movementVector = [0, -1];
} else if (hxd.Key.isDown(hxd.Key.DOWN)) {
movementVector = [0, 1];
} else if (hxd.Key.isDown(hxd.Key.LEFT)) {
movementVector = [-1, 0];
} else if (hxd.Key.isDown(hxd.Key.RIGHT)) {
movementVector = [1, 0];
} else {
isMoving = false;
}
if (isMoving) {
// Do stuff here
}
If you want to check if values of an array are same as another array, I would use this:
public static function sameAs<T>(arr1:Array<T>, arr2:Array<T>):Bool {
if (arr1.length != arr2.length) return false;
for (idx => val in arr1) if (val != arr2[idx]) return false;
return true;
}
If you would use it as static extension you can do if (movementVector.sameAs([0, 0])) ..
otherwise you need to do if if (sameAs(movementVector, [0,0])) ..
Thanks both! Extremely new to the language and I'm just dipping my toes in after coming from a Python background. Thanks for the help. Haxe is a nice language without a lot of bloat, I hope to contribute in some way if I get the chance
Array Comprehension - Haxe - The Cross-platform Toolkit
Haxe is an open source toolkit based on a modern, high level, strictly typed programming language.
https://haxe.org/manual/lf-array-comprehension.html