I'd like to detect the target language in Haxe so that I can change a function's behavior depending on which language Haxe has been piled to.
Example in Haxe-like pseudocode:
class Test() {
static function printStuff(toPrint) {
if (the target language is Java) {
System.out.println(toPrint);
} else if (the target language is C++) {
cout << toPrint;
} else if (the target language is JavaScript) {
alert(toPrint);
}
}
}
Is it currently possible to achieve this in Haxe?
I'd like to detect the target language in Haxe so that I can change a function's behavior depending on which language Haxe has been piled to.
Example in Haxe-like pseudocode:
class Test() {
static function printStuff(toPrint) {
if (the target language is Java) {
System.out.println(toPrint);
} else if (the target language is C++) {
cout << toPrint;
} else if (the target language is JavaScript) {
alert(toPrint);
}
}
}
Is it currently possible to achieve this in Haxe?
Share Improve this question asked Jul 20, 2012 at 3:18 Anderson GreenAnderson Green 31.9k70 gold badges210 silver badges339 bronze badges3 Answers
Reset to default 10You can use conditional pilation along with Haxe Magic to achieve this. For example:
#if java
untyped __java__("java.lang.System.out.println(toPrint);");
#elseif js
untyped __js__("alert(toPrint);");
#elseif ...
...
#end
Or even just use trace.
class Test()
{
static function main()
{
#if java
var language = 'java';
#elseif js
var language = 'js';
#elseif cs
var language = 'csharp';
#elseif php
var language = 'PHP'
#elseif (flash||flash8)
var language = 'flash';
#elseif cpp
var language = 'c++';
#elseif neko
var language = 'neko';
#elseif tamarin
var language = 'tamarin';
#end
trace( language );
}
}
But it should be noted that the hxml for piling this would need to have each target specified in theory it would be something generic like...
-java java
-main Test
--next
-js test.js
-main Test
--next
-cs cs
-main Test
--next
-php www
-main Test
--next
-swf test8.swf
-swf-version 8
-main Test
--next
-swf test.swf
-swf-version 9
-main Test
--next
-neko neko
--main Test
But in practice you will probably want to add other piler flags and even use -cmd to actually run examples.
Getting started with a range of targets...
'http://haxe/doc/start/
conditional pilation
'http://haxe/ref/conditionals
piler flags and options, although I may have missed a link.
'http://haxe/manual/tips_and_tricks 'http://haxe/doc/piler
Then target magic
'http://haxe/doc/advanced/magic
For each target you can use generic haxe api along with target specific libraries named after the target
'http://haxe/api
My first reply on Stackoverflow so sorry if it's a bit verbose :) also the reason I can't post proper links (limited to two).
Sorry but why did you show the untyped way?
You can have a fully typed and auto-pleted code
class Test() {
static function printStuff(toPrint) {
#if java
java.lang.System.out.println(toPrint);
#elseif js
js.Lib.alert(toPrint);
#elseif cpp
cpp.Lib.print(toPrint);
#end
}
}