Tables

Tables are special type of variable in Lua, and they take two forms- keyed tables, and unkeyed tables (also called tables and arrays). Essentially, tables are a way to take a set of data, give it a name, then give various parts of that data their own names, so that it's easy to reference them in the future.

Producing a table has different syntax than other variables. Some examples are to the side, let's go over them. First we have a keyed table with keys and values defined at the same time of the table. Then we have an array with values assigned at the creation of the table as well. It should be noted that, when doing it like the array example, the program will key the values with numbers starting at 1, so the first value is 1, the second is 2, etc. This is different from other languages, who usually start it at 0. Try not to get tripped up!

After that we have a table that is defined first, then its values in seperate lines. Note that tableExampleB.string1 = ... is equivalent to tableExampleB["string1"]. After that, we have the same example, but things are declared using []. You can put any number or string value into the brackets, and that will be the key of the value.

Getting information back out of a table works in similar ways. Like with other variables, you get their value by simple putting in its name and nothing else. An example of this is at the bottom.

Also of note: You are able to nest a table inside another table. Getting data out of it is simple, an example of it is below.

tableExampleA = {["string1"] = "value1", ["string2"] = "value2"}

arrayExample = {"value1","value2"}

tableExampleB = {}
tableExampleB.string1 = "value1"
tableExampleB.string2 = "value2"

tableExampleC = {}
tableExampleC[1] = "value1"
tableExampleC[2] = "value2"

print(tableExampleB.string1) --Will print the value of the key ["string1"] in the table tableExampleB, which should be "value1"
print(tableExampleC[1]) --Will, as you likely guessed, print the value at key [1] in the table tableExampleC

tableEx.nestedTable[1][2] --Gets the value at position one in the array nestedTable, which is a table inside the table tableEx. We also know this value happens to be an array itself, so we get the value at that array's second position