Skip to content

Instantly share code, notes, and snippets.

@jasononeil
Created December 2, 2014 01:19
Show Gist options
  • Save jasononeil/35f355e9bb48e85ae4d9 to your computer and use it in GitHub Desktop.
Save jasononeil/35f355e9bb48e85ae4d9 to your computer and use it in GitHub Desktop.
Object initialisations syntax sugar
import haxe.macro.Expr;
import haxe.macro.Context;
using haxe.macro.ExprTools;
class ObjectInit {
macro public static function init( expr:Expr, varsToSet:ExprOf<Dynamic<Dynamic>> ) {
var lines:Array<Expr> = [];
lines.push( macro var __obj_init_tmp = $expr );
switch varsToSet.expr {
case EObjectDecl(fields):
for ( field in fields ) {
var varName = field.field;
var varValue = field.expr;
lines.push( macro __obj_init_tmp.$varName = $varValue );
}
case other: Context.error( 'Expected ${expr.toString()}.init() argument to be an object declaration', expr.pos );
}
lines.push( macro __obj_init_tmp );
return { expr: EBlock(lines), pos: expr.pos };
}
}
using ObjectInit;
class ObjectInitTest {
static function main() {
var person = new Person().init({
name: "Jason",
age: 27,
likes: ["coffee","code"]
});
trace( person.name );
}
}
class Person {
public function new() {}
public var name:String;
public var age:Int;
public var likes:Array<String>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment