HaxeDoc2

(やまだぃちぅ) #1

6.5 String Interpolation.....................................


With Haxe 3 it is no longer necessary to manually concatenate parts of a string due to the intro-
duction ofString Interpolation. Special identifiers, denoted by the dollar sign$within a String
enclosed by single-quote’characters, are evaluated as if they were concatenated identifiers:
1 var x = 12;
2 // The value of x is 12
3 trace(’The value of x is $x’);
Furthermore, it is possible to include whole expressions in the string by using${expr}, with
exprbeing any valid Haxe expression:
1 var x = 12;
2 // The sum of 12 and 3 is 15
3 trace(’The sum of $x and 3 is ${x+ 3}’);
String interpolation is a compile-time feature and has no impact on the runtime. The above
example is equivalent to manual concatenation, which is exactly what the compiler generates:
1 trace("The sum of " + x +
2 " and 3 is " +(x + 3));
Of course the use of single-quote enclosed strings without any interpolation remains valid, but
care has to be taken regarding the $ character as it triggers interpolation. If an actual dollar-sign
should be used in the string,$$can be used.

Trivia: String Interpolation before Haxe 3
String Interpolation has been a Haxe feature since version 2.09. Back then, the macro
Std.formathad to be used, being both slower and less comfortable than the new string
interpolation syntax.

6.6 Array Comprehension


Comprehensions are
only listing Arrays, not
Maps


Comprehensions are
only listing Arrays, not
Maps


Array comprehension in Haxe uses existing syntax to allow concise initialization of arrays. It
is identified byfororwhileconstructs:
1 class Main {
2 static public function main() {
3 var a =[for (i in 0...10) i];
4 trace(a); // [0,1,2,3,4,5,6,7,8,9]
5
6 var i = 0;
7 var b =[while(i < 10) i++];
8 trace(b); // [0,1,2,3,4,5,6,7,8,9]
9 }
10 }
Variableais initialized to an array holding the numbers 0 to 9. The compiler generates code
which adds the value of each loop iteration to the array, so the following code would be equiva-
lent:
1 var a = [];
2 for (i in 0...10) a.push(i);
Free download pdf