Skip to content

Instantly share code, notes, and snippets.

@binki
Created December 28, 2016 21:21
Show Gist options
  • Save binki/389321bf544c4b305989c38fe0e852b6 to your computer and use it in GitHub Desktop.
Save binki/389321bf544c4b305989c38fe0e852b6 to your computer and use it in GitHub Desktop.
Haxe coalesce macro
$ haxe --run Test
Test.hx:9: 53
Test.hx:11: 43
import haxe.macro.Expr;
class Test {
static function main() {
var x = 2;
var y = 53;
var z = 43;
x = null;
trace(coalesce(x, y, z));
y = null;
trace(coalesce(x, y, z));
}
macro static function coalesce<T>(e:Array<ExprOf<T>>):Expr {
return macro {
var v = null;
$b{[for (expr in e) macro { if (v == null) { v = ${expr} } }]}
v;
};
}
}
// Generated by Haxe 3.4.0
(function () { "use strict";
var Test = function() { };
Test.main = function() {
var x = 2;
var y = 53;
x = null;
var v = null;
if(v == null) {
v = x;
}
if(v == null) {
v = 53;
}
if(v == null) {
v = 43;
}
console.log(v);
y = null;
var v1 = null;
if(v1 == null) {
v1 = x;
}
if(v1 == null) {
v1 = y;
}
if(v1 == null) {
v1 = 43;
}
console.log(v1);
};
Test.main();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment