Numbers and conversions
Number types
| Type | Meaning |
|---|---|
int |
32-bit signed integer (same as int32) |
float |
32-bit float |
int8, int16, int32, int64 |
Signed integers |
uint8, uint16, uint32, uint64 |
Unsigned integers |
float64 |
64-bit float |
bool |
true / false |
There is no number type: the compiler says 'number' was removed; use 'int' or 'float'.
Literals
- A literal without a
.is anint; with a.(or an exponent like1e3) it is afloat. - Integer literals must fit in 32 bits.
- Hex
0xff, binary0b1010, octal0o17and_separators (1_000) are spelled as in TypeScript.
Conversions
Conversions follow C's usual rules, with one exception:
- Integers convert implicitly to any other integer type and to
float/float64. - A float never converts to an integer implicitly. Write
int(x),uint8(x)and so on. Every number type name works as a conversion function.
export function main(): void {
const f: float = 7; // int to float: implicit
const i = int(2.9); // float to int: explicit, truncates
const small = uint8(300); // wraps
const back = int(-1.5);
print(f, i, small, back, float64(1) / 3);
}
7 2 44 -1 0.333333333333333
Writing const i: int = 2.5; is an error: cannot convert float to int.
Arithmetic rules
export function main(): void {
print(7 / 2, 7.0 / 2, -7 / 2, 7 % 3, 7.5 % 2);
const zero = 0;
print(10 / zero, 10 % zero); // 0 and 0; dev builds log an error
print(int32(2147483647) + 1); // wraps
print(1 << 33, -4 >> 1, -1 >>> 1); // shift counts wrap to the width
print(round(2.5), round(-2.5));
}
3 3.5 -3 1 1.5
0 0
-2147483648
2 -2 2147483647
3 -2
- Integer division truncates toward zero.
- Integer
/or%by zero gives0; in a game's dev build it also logs an error with the file and line. - Signed and unsigned overflow wraps (two's complement).
%on floats isfmod.- Shift counts wrap to the operand's width (
1 << 33is1 << 1). - An explicit float-to-integer conversion truncates and wraps; infinity and NaN give 0.
Comparing numbers
== is strict: both sides must have the same type. Comparing an int with a float is an
error (operator '==' does not accept int and float); convert one side first:
float(i) == x. Relational operators (<, >=, ...) use the usual conversions.
Printing
Floats print with up to 9 significant digits, float64 with up to 17.
(42).toString() and string(3.5) convert numbers to strings.