Haxe macro: copying expressions from another Type

I was playing around inspecting the contents of other Types through haxe macro when I found that I can copy expressions from another type very easily. I think I should write it down as a note for myself.

A possibly interesting use-case is that Haxe doesn’t inline your function even you marked it as inline, if you try to store the function in a variable.

static function main() {
  var t = test; // outputs `var t = test;` instead of `var t = function() {trace("test");}`

static inline function test() trace("test");

However, with the following simple macro trick, we can assign a function to a variable “inlined”



I am trying to copy some of the contents of this class to Main


The output is something like this:
Note that the the original field Test.test is copied into Main and assigned to a variable called myFunc


The magic happens here

Final note:

This is fun and may be useful. However, one should pay attention that this may cause errors if the copied expression contains Types that is not found in the current context. Because the Type information are lost during the TypedExpr-to-Expr conversion.

Leave a Reply

Your email address will not be published. Required fields are marked *