Understanding Tables
Tables are the only variable type in TableScript. They are a collection of strings, but can also represent integers, booleans and strings.
Internally, they are represented as a string collection or as a number (used to save resources on integer tables).
Tables as string collections
Elements of the table can be accessed in TableScript in two ways:
- Using the dot syntax
- Using the square brackets syntax
//Table initialization
tab a = ["a", "b", "c"];
//Dot syntax
print(a.0); //prints a
//Square brackets syntax
print(a[1]); //prints b
//Out of bounds index returns []
print(a[100]);
//Negative indices
print(a[-1]); //prints c
Negative indices start by the end, -1 being the last element, -2 the previous one and so forth.
The square syntax allows to use full expressions as indices, something the dot syntax doesnt.
You can also access a random element using the random keyword.
Tables as integers
A table's length is its value as an integer.
Also, you can access a tables length using the length keyword. This keyword returns a number table (table made up of empty strings):
//Table initialization
tab a = ["a", "b", "c"];
print(a.length == ["", "", ""] ? "true" : "false"); //Prints true
This is also what happens when using numbers.
For example 0 represents a table of length 0([]) and 3 represents a table of length 3(["", "", ""]):
//Table initialization
tab a = 3;
print(a == ["", "", ""] ? "true" : "false"); //Prints true
Numbers allow you to set negative lengths for tables, something that doesnt make much sense, and is turned positive as soon as they stop having empty elements:
//Table initialization
tab a = -4;
a.0 = "h"; //Setting an element
print(a.length == 1 ? "true" : "false"); //Prints true
Thats why it is recommended not using negative number tables for other things that arent numbers.
Tables as booleans
Tables are defined as being true when their length is greater than 0.
Many operators that return booleans (such as ==) return either 0 or 1 for false and true:
tab a = ["a", "b"] == ["a", "b", "c"];
print(a == 0 ? "true" : "false"); //Prints true
Also, for conditions in statements, any table can be used:
tab a = ["a", "b"];
if a{
print("a is greater than 0");
}
Tables as strings
Tables are collections of strings, so to use them as strings, all elements are flattened into a length 1 table.
This is the same that happens with the reduction operator(postfix ^):
tab a = ["a", "b", "c"];
print(a^ == "abc" ? "true" : "false"); //Prints true
Also, initializing tables as a single string creates them with length 1:
print("abc" == ["abc"] ? "true" : "false"); //Prints true
In the next tutorial, we will go over all the operators available in TableScript.