# Tables

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
 Tutorial: Tables This script will introduce you to Tables, and show you some ways to use them. If you have experience with other languages, a table is roughly equivalent to an array. Objective An understanding of the usage and purpose of Tables Prerequisites A basic understanding of Variables.

## Why are Tables Useful?

Tables can simplify code considerably, by grouping like variables and functions together.

In this example, we're getting a list of student's names Code without tables

```local StudentName1 = "Andrew"
local StudentName2 = "Alfred"
local StudentName3 = "Alex"
local StudentName4 = "Amber"
local StudentName5 = "Alice"
```

Code with tables

```local StudentNames = {"Andrew", "Alfred", "Alex", "Amber", "Alice"}
```

As you can see, the first example needs 5 unique variables being defined individually, while the second example, using the table, is all one line with one variable.

Note the { and }, this is how you spot a table. Anything between them is a variable to be stored in the table. A table is not restricted to one variable type, and you can even store tables within tables if you wish

## Using the Table

There are a number of ways to set the values in a table. The first, as shown above, is the simplest method, and will give each value a unique number as the "key". The key is simply the location in the table, it's usually a number or string. This method always clears the contents of the table and replaces it with what you've specified. Note that setting a table to "{}" is valid, and is commonly used if the values don't need to, or can't, be set immediately. You may find yourself using "Variable={}" often. Setting a specific key with this method is relatively simple, you just use the asignment operator "=" and treat the key as a variable

```local Table = {Key1 = "First key!", Key2 = "Second key!"}
```

It can also be defined over multiple lines, to help with readability, if you end the line with a comma rather than the } to close it. Just remember to add the } when you're done.

```local Table = {"Stuff", 1, 2, "More stuff",
3, "Some strings",
function() end}
```

Another method is to use brackets, [ and ], to specify the key. This method requires the table to have already been created, using { and }, otherwise it will give you an error. Using this method will treat it as a regular variable, so you can both set and read the value with this method. This method is commonly used for getting a value when the key is a number.

```local Table = {}
Table["Boolean"] = true

if Table["Boolean"] then print("The value is true!") end
```

If you need to reference a table within a table using this method, you can simply add another [ ]

```local Table = {"Value", 2, {true, false}}

if Table[3][2] then print("The value is true!") else print("The value is false!") end
```

A third method is to simply add the key onto the end of the table name, separated by a ".". Like the previous method, this method requires the table to already exist. It can also be treated as a regular variable, as above. This method is commonly used for when the key is a string.

```local Table = {}

Table.key = true
if Table.key then print("True!") end
```

As with the second method, to index a table within a table you just add the second key to the end. Note that these methods are interchangeable, and can all be used at the same time.

It is not advisable to have many tables inside each other, especially if they are similarly named

```local Table = {String = "This is a string!", Table = {Number = 2, Table = {func = write, Table = {Bool = true} } }}

if Table["Table"].Table.Table.Bool then print("True!") end
```

If you don't mind being restricted to number keys, you could use the table.insert(Table, [Position,] Value ) function.

```local Table = {"One"}
table.insert(Table, "Three") --This inserts the string "Three" to the end of the table (At key 2)
table.insert(Table, 2, "Two") --This inserts the string "Two" to key 2, pushing the string "Three" up to key three
--End result, Table[1] is One, Table[2] is Two, Table[3] is Three
```

## Tables and Loops

When you combine tables and loops, they suddenly become a lot more useful. You can run through a table easily, using or changing each value.

```local Table = {"Hello! ", "This string ", "was read from ", "a table!", "\n"}
for i=1,#Table do
write( Table[i] )
end
```

This will write "Hello! This string was read from a table!" followed by a new line. You may notice there's a "#" in front of Table, this simply returns the number of values in the table. It can also be used to get the length of a string.

The standard for loop does, however, come with an inherent disadvantage in that it can only (easily) access consecutive numerical strings, ie 1,2,3 but not 1,2,4. to get around this, we can use "pairs" and "ipairs". "pairs" and "ipairs" use a table to loop, by running through the keys and values for the number that exist in the table.

```local Table = {StartTime = 0.5, EndTime = 1.5}

for key,value in pairs( Table ) do
print(tostring(key)..": "..tostring(value))
end
```

This will output equivalent to "EndTime: 1.5: StartTime: 0.5". Note that ipairs is identical to pairs, except it tries to do it in order.

## Saving Tables to Files

To save a table to file in ComputerCraft it must first be converted to a string using textutils.serialize (table.save is not included). Example function to save a table to a file:

```function save(table,name)
local file = fs.open(name,"w")
file.write(textutils.serialize(table))
file.close()
end
```

To load, the string must be converted back to a table using textutils.unserialize. Example function to load a table from a file:

```function load(name)
local file = fs.open(name,"r")
file.close()
return textutils.unserialize(data)
end
```

## Using Tables as Matrices

Tables can provide the functionality of matrices by "nesting" tables inside one another. Example function to make an M by N matrix:

```function matrix(M,N)
mt = {}
for i=1,M do
mt[i] = {}
for j=1,N do
mt[i][j] = 0
end
end
end
```

Example of a serialized 3 by 4 matrix:

```{[1]={[1]=0,[2]=0,[3]=0,},[2]={[1]=0,[2]=0,[3]=0,},[3]={[1]=0,[2]=0,[3]=0,},[4]={[1]=0,[2]=0,[3]=0,},}
```