Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
@:enum abstract Something(Int) autoInt() macro
import haxe.macro.Context;
import haxe.macro.Expr;
class Macros {
macro public static function autoInt():Array<Field> {
var fields = Context.getBuildFields();
var t = switch(Context.getLocalClass().get().kind) {
case KAbstractImpl(c):
switch(c.get().type) {
case TAbstract(t, _):
t.get().name == "Int";
case _: false;
}
case _: false;
}
if (!t) Context.error("This macro only works on abstracts whose base type is Int", Context.currentPos());
var i = 0;
for (field in fields) {
switch(field.kind) {
case FVar(_, _):
field.kind = FVar(null, macro { cast $v{i++}; });
case _:
}
}
return fields;
}
}
class Main {
public static function main() {
trace(GamepadButton.DPAD_UP);
trace(GamepadButton.DPAD_LEFT);
trace(GamepadButton.A);
trace(GamepadButton.L_STICK_AXIS_X_MINUS);
}
}
@:build(Macros.autoInt())
// var A = 0; is needed for Haxe versions 3.2.1 and lower. Haxe 3.3 doesn't need the = 0
@:enum abstract GamepadButton(Int) {
var DPAD_UP = 0;
var DPAD_DOWN = 0;
var DPAD_LEFT = 0;
var DPAD_RIGHT = 0;
var A = 0;
var B = 0;
var X = 0;
var Y = 0;
var BACK = 0;
var START = 0;
var L_STICK_BUTTON = 0;
var R_STICK_BUTTON = 0;
var L_STICK_AXIS_X_PLUS = 0;
var L_STICK_AXIS_X_MINUS = 0;
var L_STICK_AXIS_Y_PLUS = 0;
var L_STICK_AXIS_Y_MINUS = 0;
var R_STICK_AXIS_X_PLUS = 0;
var R_STICK_AXIS_X_MINUS = 0;
var R_STICK_AXIS_Y_PLUS = 0;
var R_STICK_AXIS_Y_MINUS = 0;
var L_BUTTON = 0;
var R_BUTTON = 0;
var L_TRIGGER = 0;
var R_TRIGGER = 0;
}
(function (console) { "use strict";
var Main = function() { };
Main.main = function() {
console.log(0);
console.log(2);
console.log(4);
console.log(13);
};
Main.main();
})(typeof console != "undefined" ? console : {log:function(){}});

This would be a nice snippet for the Haxe Code Cookbook 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment