Reputation: 3132
I am trying to add a static variable and a static function to all instances of a class and its child classes using the @:build
and @:autoBuild
macros.
I managed to get the static variable working, but I have no idea how to "build" the function from the various EFunction
, EFor
, etc.
Here is the code I have so far:
macro static public function addGetId() :Array<Field>
{
var fields : Array<Field> = Context.getBuildFields();
// The static _id field
var idField = {
name : "_id",
doc : null,
meta : [],
access : [AStatic, APrivate],
kind : FVar(macro : Int, macro -1),
pos : Context.currentPos()
};
// The getId function field
var getIdField = {
name : "getId",
doc : "Returns the ID of this command type.",
meta : [],
access : [AStatic, APublic],
kind : FFun({
params : [],
args : [],
expr: // What do I have to write here???
ret : macro : Int
}),
pos : Context.currentPos()
};
fields.push(idField);
fields.push(getIdField);
return fields;
}
Here is how the function that I want to add would look like in normal code, if it was actually in the .hx file:
public static function getId() : Int
{
if (_id == -1)
{
_id = MySingleton.getInst().myGreatFunction()
}
return _id;
};
So it references the newly added _id
variable as well as some singleton class function.
So: How would the complete getIdField()
look like?
Bonus Question:
My biggest problem with this is the complete lack of documentation on these features as well as any useful examples in the manual. Is there any actually useful tutorial for creating functions like this?
Bonus Bonus Question:
What is the difference between params
and args
in FFun
?
Upvotes: 5
Views: 1051
Reputation: 34148
You can make use of reification to write the body of the function like you would in regular Haxe code:
expr: macro {
if (_id == -1) {
_id = 0;
}
return _id;
},
params
is a list of type parameters, args
is the list of arguments the function receives. There's a trivia section about this on the Haxe Manual:
Trivia: Argument vs. Parameter
In some other programming languages, argument and parameter are used interchangeably. In Haxe, argument is used when referring to methods and parameter refers to Type Parameters.
Upvotes: 5