Quick Tip: Haxe compile time constants

macro

In case you have not yet started with haxe macros (The Haxe macro system allows powerful compile-time code-generation without modifying the Haxe syntax.), you may find it difficult to implement something like inline constants you were used in your flash projects. Lets imagine you just want to “embed” a version number of your app right into the app and access it at a runtime, or you want to show a build date. In Haxe you have the option to use macros for this purpose, and this would be just a tiny piece of iceberg macros let you do. Here is a simple example how to do that.

Consider following as Main.hx source:

import haxe.macro.Context;

class Main
{
	public static function main()
	{
		new Main();
	}

	public function new()
	{
		untyped alert(getCompilerVariable("abc")); // would say "def"
		untyped alert(getCompilerVariable("ghi")); // would say "jkl"
	}

	macro public static function getCompilerVariable(key:String)
	{
		return Context.makeExpr(Context.definedValue(key), Context.currentPos());
	}
}

…now compile with -D argument:

haxe -cp src Main.hx -js Main.js -main Main -D abc=def -D ghi=jkl

Now, that was easy, you may want to see Main.js and notice the macro function has been inlined:

(function () { "use strict";
var Main = function() {
	alert("def");
	alert("jkl");
};
Main.main = function() {
	new Main();
}
Main.main();
})();

In case you are interested in build date you can use following:

macro public static function getBuildDate()
{
	return Context.makeExpr(Date.now().toString(), Context.currentPos());
}

…this would get inlined to something like:

2013-06-24 16:16:58

Where to go from here:

Leave a comment

Please be polite and on topic. Your e-mail will never be published.