Haxe "global" functions and variables

608 views
Skip to first unread message

Jeff Ward

unread,
May 5, 2016, 11:44:08 AM5/5/16
to Haxe
Hi guys,

I tweeted about it, but I thought I'd write something here as well --

I find it rather slick that, while you can't define global functions and variables in Haxe, you can easily import static functions and variables to allow you to use the same syntax:

Global.hx

class Global {
public static function parseInt(s:String):Int { return Std.parseInt(s); }
public static function int(f:Float):Int { return Std.int(f); }
public static function is(v:Dynamic, t:Dynamic):Bool { return Std.is(v, t); }
public static function typeof(o:Dynamic):Type.ValueType { return Type.typeof(o); }
public static var DEBUG_LEVEL:Int = 3;
}
Main.hx
import Global.*;
class Main
{
public static function main()
{
trace("parseInt: " + parseInt("51"));
trace("5 is int? " + is(5, Int));
trace("int(Math.PI) = " + int(Math.PI) );
trace(typeof([]));
trace("DEBUG_LEVEL > 2 ? " + (DEBUG_LEVEL>2));
}
}
While there are the right times and places to use and not use global-like syntax -- I don't really care to debate that in this thread -- I appreciate that a simple import statement can allow this syntax if you have such a preference.

Cheers,
-Jeff

Rafael Oliveira

unread,
May 5, 2016, 4:51:13 PM5/5/16
to Haxe
I found this sometime ago. This is great if are building a library for teach programming, and you want a library with very simple code. I used this to make a engine with a api similar to pico8. In pico8 the api is just a collection of functions.

Christian Afonso Ferreira

unread,
May 5, 2016, 7:22:14 PM5/5/16
to Haxe
I was using it with a log class but I got many issues with compiler errors being reported in the source of the log class instead of the actual position.
Maybe because they are macro functions... Don't know for sure.

Juraj Kirchheim

unread,
May 6, 2016, 6:42:55 AM5/6/16
to haxe...@googlegroups.com
Yep, it's a nice comfort feature. 

The most useful application by far is `import js.Browser.*;` ... solves 95% of the issues you get when copy-pasting JS code into Haxe.

--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages