Created
December 2, 2014 01:19
-
-
Save jasononeil/35f355e9bb48e85ae4d9 to your computer and use it in GitHub Desktop.
Object initialisations syntax sugar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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