In haxe is there some way to get the last element of an array other than using arr[arr.length-1] as key? I would like to avoid needing a reference to the array.
No, but you could create a static extension for it:
using ArrayExtensions;
class Main {
static function main() {
var a = [1, 2, 3];
trace(a.last()); // 3
}
}
class ArrayExtensions {
public static inline function last<T>(a:Array<T>):T {
return a[a.length - 1];
}
}
Alternatively, you could overload the array access operator with a custom abstract to get Python-style negative indices:
class Main {
static function main() {
var a:PythonArray<Int> = [1, 2, 3];
trace(a[-1]); // 3
}
}
@:forward
abstract PythonArray<T>(Array<T>) from Array<T> to Array<T> {
@:arrayAccess function get(i) {
return if (i < 0) this[this.length - i * -1] else this[i];
}
@:arrayAccess function set(i, v) {
return if (i < 0) this[this.length - i * -1] = v else this[i] = v;
}
}
This has the downside that the array has to be typed as that abstract.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With