Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haxe get array last element

Tags:

arrays

haxe

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.

like image 262
blues Avatar asked Sep 16 '26 06:09

blues


1 Answers

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.

like image 192
Gama11 Avatar answered Sep 21 '26 02:09

Gama11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!