Using sprintf with Haxe

In contrast to ActionScript, Haxe allows you to customize the trace() function to better fit your requirements. For example, you can format or delegate the input to your favorite logger, resulting in less verbose code.
My library supports the sprintf syntax, so let’s take a look on how to use it seamlessly with trace().

First, we need to redefine the behavior of the trace() function, which is done by calling Root.init():

class Main
    public static function main() {
        de.polygonal.core.Root.init(onInit, true);

    static function onInit() {
        trace("entry point...");

From now on, trace() calls are redirected to Root.log().debug(…), and the default log handler writes to flashlog when targeting Flash. Compiling and running the above example, the log file should look like this:

001 DEBUG line 0154 Root::_onInit()               log initialized.
002 DEBUG line 0016 Test::new()                   entry point...

BTW, I’m using a wonderful little log viewer called Baretail. We are now ready to trace out sprintf formatted data. This is the regular way…

import de.polygonal.core.fmt.Sprintf;

trace(Sprintf.format("My name is %s.", ["Michael"])); //My name is Michael.

…but thanks to Haxe it all boils down to this:

trace("My name is %s.", "Michael"); //My name is Michael.

Here are some more examples:

trace("x=%02d", 3); //x=03

trace("PI equals %.3f", Math.PI); //PI equals 3.142

trace("%#x", 255); //0xff

trace("%.2f%%", 0.95); //0.95%

trace("[%+10.3f]", 1.1); //[    +1.100]

And if you want to get rid of all trace statements, you simply compile with --no-traces ;)

1 thought on “Using sprintf with Haxe”

Comments are closed.