<a id="data-types-and-literals"></a>

# Data types and literals

HSL has multiple data types; *strings*, *booleans*, *numbers*, *arrays* (which also works as an ordered map to store key-value pairs, similar to PHP’s [array](http://php.net/manual/en/language.types.array.php)), *objects* (created by [classes](structures.html.md#class-statement)) and *functions* (both anonymous functions and named function pointers). Some of these data types may be represented as literals. There is also a *none* (or *null*) data type that is often used to represent errors or no valid value or response (e.g. a [return](structures.html.md#return) statement without a value or a failed [`json_decode()`](functions.html.md#json_decode) both of which return *none*).

<a id="boolean"></a>

<a id="id1"></a>

## Boolean

The keywords `true` and `false` represent boolean true and boolean false, they are treated as *1* and *0* in arithmetics operations.

> **Warning**
> 
> Boolean `true` and `false` should not always be used in if statement, if you are not fully aware of the [truthiness](operators.html.md#truthtable) and loose comparison.
> 
> ```hsl
> if (5 == true) { } // false: 5 is not equal to 1
> if (5) { } // true: 5 is not false, hence true
> ```

<a id="number"></a>

<a id="id2"></a>

## Number

The number type is a double-precision 64-bit [IEEE 754](http://en.wikipedia.org/wiki/Double-precision_floating-point_format) value. If converted to a string it will be presented in the most accurate way possible without trailing decimal zeros. A numeric separator (`_`) is allowed between digits for readability, it does not affect the value of the number.

```hsl
echo 1.0; // 1
echo 1_000_000; // 1000000
```

> **Note**
> 
> The number type can safely represent all integers between  *+/-9007199254740991* (the equivalent of `(2 ** 53) - 1`).

> **Warning**
> 
> After some arithmetic operations on floating point numbers; the equality (`==`) of two floating point numbers may not be true even if they mathematically “should”. This caveat is not unique to HSL, instead it is the result of how computers calculates and stores [floating point numbers](http://en.wikipedia.org/wiki/Floating_point). Arithmetic operations on *numbers* without decimals are not affected.

<a id="hexadecimal"></a>

<a id="id3"></a>

### Hexadecimal

Numbers may be entered in hexadecimal form (also known as base 16) using the `0x` prefix; followed by `[0-9a-f]+`. A numeric separator (`_`) is allowed between digits for readability, it does not affect the value of the number.

```hsl
echo 0xfa; // 250
echo 0x00_fa; // 250
```

<a id="octal"></a>

<a id="id4"></a>

### Octal

Numbers may be entered in octal form (also known as base 8) using the `0o` prefix; followed by `[0-7]+`. A numeric separator (`_`) is allowed between digits for readability, it does not affect the value of the number.

```hsl
echo 0o372; // 250
```

<a id="binary"></a>

<a id="id5"></a>

### Binary

Numbers may be entered in binary form (also known as base 2) using the `0b` prefix; followed by `[0-1]+`. A numeric separator (`_`) is allowed between digits for readability, it does not affect the value of the number.

```hsl
echo 0b11111010; // 250
echo 0b1111_1010; // 250
```

<a id="string"></a>

<a id="id6"></a>

## String

There are two kinds of string literals, *double-quoted strings* and *raw strings*. Double-quoted strings support language features such as variable interpolation and escape sequences. Most functions (e.g. [`length()`](functions.html.md#length) and [`str_slice()`](functions.html.md#str_slice)) are **not** [UTF-8](http://en.wikipedia.org/wiki/UTF-8) aware, with the exception of [regular expression](operators.html.md#regex) matching (e.g. [`pcre_match()`](functions.html.md#pcre_match)) which may be configured to be UTF-8 aware with the [/u](#patternmodifiers) modifier.

<a id="doublequoted"></a>

<a id="double-quoted-string"></a>

### Double-quoted string

Variable interpolation replaces `$variable` placeholders within string literals. Variables are matched in strings with the following pattern `$[a-zA-Z_]+[a-zA-Z0-9_]`. If needed there is also a more explicit syntax `${variable}` (which allows variables mid-words). Interpolating an undeclared variable raises a runtime error.

```hsl
"$variable"
"${variable}abc"
```

| Escape sequence   | Meaning                       |
|-------------------|-------------------------------|
| `\\`              | Backslash (`\`)               |
| `\"`              | Double quote (`"`)            |
| `\$`              | Dollar sign (`$`)             |
| `\n`              | ASCII Linefeed (LF)           |
| `\r`              | ASCII Carriage Return (CR)    |
| `\t`              | ASCII Horizontal Tab (TAB)    |
| `\xhh`            | Character with hex value *hh* |

<a id="rawstring"></a>

<a id="raw-string"></a>

### Raw string

Raw strings do not support variable interpolation nor escape sequences. This make them suitable for [regular expressions](operators.html.md#regex). Raw strings start and end with **two single quotes** on each side `''`, with an optional delimiter in between. The delimiter can be any of `[\x21-\x26\x28-\x7e]*`; simply put any word.

```hsl
''raw string''
'DELIMITER'raw string'DELIMITER'
'#'raw string'#'
```

> **Note**
> 
> There is no performance difference between double-quoted and raw strings containing the same value. However if special characters needs to be escaped then raw string are recommended for clarity.

<a id="regextype"></a>

<a id="regex"></a>

## Regex

A regex literal is a pre-compiled regular expression object. The regular expression implementation is “Perl Compatible” (hence the function names `pcre_...`), for syntax see the [perlre](http://perldoc.perl.org/perlre.html) documentation. See supported [pattern modifiers](#patternmodifiers).

```none
#/pattern/[modifiers]
```

This type can mainly be used with the [regular expression](operators.html.md#regex) operators and also as argument to the [`pcre_match()`](functions.html.md#pcre_match) family of functions.

```none
if ($string =~ #/hello/i) {}
if (pcre_match(#/hello/i, $string)) {}
```

<a id="patternmodifiers"></a>

<a id="pattern-modifiers"></a>

### Pattern modifiers

Use pattern modifiers to change the behavior of the pattern engine, they have the capability to make the match case-insensitive and activate UTF-8 support (where one UTF-8 characters may be matched using only one dot) etc.

| Modifier   | Internal define   | Description                                                             |
|------------|-------------------|-------------------------------------------------------------------------|
| i          | PCRE2_CASELESS    | Do case-insensitive matching                                            |
| m          | PCRE2_MULTILINE   | See [perl](http://perldoc.perl.org/perlre.html#Modifiers) documentation |
| u          | PCRE2_UTF8        | Enable UTF-8 support                                                    |
| s          | PCRE2_DOTALL      | See [perl](http://perldoc.perl.org/perlre.html#Modifiers) documentation |
| x          | PCRE2_EXTENDED    | See [perl](http://perldoc.perl.org/perlre.html#Modifiers) documentation |
| U          | PCRE2_UNGREEDY    | See [perl](http://perldoc.perl.org/perlre.html#Modifiers) documentation |
| X          |                   | Not used                                                                |

> **Warning**
> 
> The `X` flag has been deprecated (since 6.7) and is now enabled by default. The `X` flag was used to enable stricter pattern validation.

<a id="arraytype"></a>

<a id="id10"></a>

## Array

An array is a very useful container; it can act as an indexed array (automatically indexed at zero, or the highest current index + 1) or as an ordered map (associative array) with any and mixed data types as key and value. The short array syntax for literal arrays `[]` is recommended.

```hsl
// indexed arrays
echo array("value", "value2");
echo ["value", "value2"];
echo [0 => "value", 1 => "value2"];

// associative arrays
echo array("key" => "value");
echo ["key" => "value"];

// multidimensional arrays
echo ["key" => ["key" => "value"]];

// automatic indexing
echo ["foo", 3=>"bar", "baz"]; // 0=>foo, 3=>bar, 4=>baz

// delete index
$foo = [];
$foo["bar"] = "hello";
unset($foo["bar"]);
echo $foo; // []
```

> **Note**
> 
> Accessing any element in a zero indexed array using the *subscript* or *slice* operator is very fast (it has the complexity of *O(1)*).

<a id="none"></a>

<a id="function"></a>

## Function

Both *anonymous functions* (closures) and *named function pointers* (references to functions) are available. This datatype is primarly used to be passed as callbacks to other functions.

<a id="anonymous-functions"></a>

<a id="id11"></a>

### Anonymous functions

An anonymous function is a unnamed [function](structures.html.md#user-function), it can be passed as value to a function or assigned to a variable. An anonymous function can also act as a [closure](structures.html.md#closure). The [global](structures.html.md#global-keyword) variable scoping rules apply.

```hsl
$multiply = function ($x, $y) { return $x * $y; };
echo $multiply(3, 5); // 15
```

<a id="named-function-pointers"></a>

### Named function pointers

A named function pointer is a reference to a named function. It can reference both a [builtin function](functions.html.md) or a [user-defined function](structures.html.md#user-function). Prepending the function name with the [builtin](structures.html.md#builtin-keyword) keyword works as expected.

```hsl
function length($str) { return 42; }

$function = length;
echo $function("Hello"); // 42

$function = builtin length;
echo $function("Hello"); // 5
```

<a id="object"></a>

## Object

An object is an instance type of a [class](structures.html.md#class-statement) statement or of a builtin class (such as [`Socket`](functions.html.md#Socket) or [`File`](functions.html.md#File)).

<a id="Iterator"></a>

### *class* Iterator

The builtin iterator class is used for iterators such as [generators](structures.html.md#generator-object) or [`Map`](functions.html.md#Map).

<a id="Iterator.next"></a>

#### next()

Return the next value from the iterator.

* **Returns:**
  iterator data
* **Return type:**
  array

The iterator data returned is an associative array with two fields

> * `value` (any) the value of the iterator
> * `done` (boolean) if the iteration/iterator is completed.

> **Note**
> 
> Some iterators (such as [`Map`](functions.html.md#Map)) return an array containing a [key, value] as `value`. The foreach statement will
> then map these to its key and value variables.

<a id="id12"></a>

## None

This data type is represented by the keyword `none`. It may be used to indicate error-result or no return value from functions such as. [`json_decode()`](functions.html.md#json_decode) (in case of a decode error) or from a user-defined [function](structures.html.md#user-function) with no or an empty [return](structures.html.md#return) statement. This data type should **not** be used as an argument to other built-in functions as it yields **undefined** behavior for the most part. The only functions safe to handle this data type is:

> * [`is_number()`](functions.html.md#is_number)
> * [`is_boolean()`](functions.html.md#is_boolean)
> * [`is_string()`](functions.html.md#is_string)
> * [`is_array()`](functions.html.md#is_array)
> * [`is_function()`](functions.html.md#is_function)

```hsl
$obj = json_decode("...");
if ($obj == none)
        echo "None";
```
