Created
February 19, 2014 18:29
-
-
Save Simn/9098351 to your computer and use it in GitHub Desktop.
initLocals macro
This file contains hidden or 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
class Main { | |
var arg1:Int; | |
var arg2:String; | |
var arg3:Bool; | |
function new(arg1 = 0, arg2 = "foo", arg3 = false) { | |
MyMacro.initLocals(); | |
} | |
static public function main() { | |
var m = new Main(); | |
trace(m.arg1, m.arg2, m.arg3); | |
} | |
} |
This file contains hidden or 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 Lambda; | |
class MyMacro { | |
macro static public function initLocals() { | |
var locals = Context.getLocalVars(); | |
var fields = Context.getLocalClass().get().fields.get(); | |
var exprs = []; | |
for (local in locals.keys()) { | |
if (fields.exists(function(field) return field.name == local)) { | |
exprs.push(macro this.$local = $i{local}); | |
} | |
} | |
var eInit = macro $b{exprs}; | |
return eInit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My way: https://github.com/AxGord/Pony/blob/haxe3/pony/time/DTimer.hx#L49
https://github.com/AxGord/Pony/blob/haxe3/pony/magic/Declarator.hx#L62
Can be used if need init not all args, and help if class have many arguments.