Reputation: 3084
I'm adding getter and setters to a variable using haxe macros, now I'm stuck trying to call a static function from within the newly generated setter:
public static function build():Array<Field> {
//.........
// create setter
var setterBody = macro {
$variableRef = v;
// mypackage.MyClass.myFunc(this) <-------- DOES NOT WORK!!
return $variableRef;
};
newFields.push({
pos: Context.currentPos(),
name: "set_" + field.name,
meta: [],
kind: FieldType.FFun({
ret: readType,
params: [],
expr: setterBody,
args: [{
value: null,
type: readType,
opt: false,
name: "v"
}]
}),
doc: "",
access: []
});
In the code above I can't find a way to call MyClass.myFun(this)
, I don't know how to generate that code for the setter, this
refers to the instance of the object where the setter is called.
Thank you very much.
Upvotes: 2
Views: 549
Reputation: 6008
Without a more complete example it's hard to know what went wrong. What I can do is show you code that works:
TiagoLrMacroTest.hx:
@:build( TiagoLrMacro.build() )
class TiagoLrMacroTest {
public static function main() {
var test = new TiagoLrMacroTest();
test.name = "hello";
}
function new() {}
public var name(default,set):String;
}
class MyStaticClass {
public static function staticMethod( a:TiagoLrMacroTest ) {
trace( a.name );
}
}
TiagoLrMacro.hx
import haxe.macro.Expr;
import haxe.macro.Context;
class TiagoLrMacro {
public static function build():Array<Field> {
var fields = Context.getBuildFields();
var setterBody = macro {
name = v;
TiagoLrMacroTest.MyStaticClass.staticMethod( this );
return name;
};
fields.push({
pos: Context.currentPos(),
name: "set_name",
meta: [],
kind: FieldType.FFun({
ret: macro :String,
params: [],
expr: setterBody,
args: [{
value: null,
type: macro :String,
opt: false,
name: "v"
}]
}),
doc: "",
access: []
});
return fields;
}
}
Result (Haxe 3.1.3):
TiagoLrMacroTest.hx:15: hello
The one common gotcha I run into with calling static methods in macros is that imports are not respected, so you have to use full type paths like mypackage.MyClass.myFunc(this)
, but you are already doing this, so the error must be somewhere else in your code. Happy macro-ing :)
Upvotes: 3