Tables: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Ozzypig
>Ozzypig
No edit summary
Line 1: Line 1:
A '''table''' is a useful way to store multiple values in one value. It is called a table because it acts like a grid with two columns:
A '''table''' is a data type in Lua that is a useful way to store multiple values. It is called a table because it acts like a grid with two columns:


{| border="1"
{| border="1"
Line 7: Line 7:
|}
|}


The ''key'' column is used to find a row in the table, and the ''value'' is the value that is stored in that row. Both the key and value can be any Lua value (numbers, strings, the values of variables, [[Part]]s etc., even other tables!) except [[nil]].
The ''key'' column is used to find a row in the table, and the ''value'' is the value that is stored in that row. Both the key and value can be any Lua value (numbers, strings, [[Part]]s etc., and even other tables) except [[nil]]. Lua tables do not have to use either numbers, strings or tables as keys. Any combination of key types can be used.
 
The <code>#</code> operator will return the amount of keys that are numbers.


__TOC__
__TOC__
Line 53: Line 55:
</pre>
</pre>


''The commas and semicolons are are important!'' If they are not there, Lua will give an error message saying it expects the closing curly bracket ('''}''') at the line where the next value appears.
''The commas and semicolons are are important!'' If they are not there, Lua will give an error message saying it expects the closing  
curly bracket ('''}''') at the line where the next value appears.
 
If you are defining a key that is a string, you may simply state the string without square brackets nor quotes, so long as they follow the naming guidelines of Lua:
 
<pre>
myOtherTable = {
    apple = "red",
    orange = "orange",
    banana = "yellow"
}
 
print(myOtherTable[1], myOtherTable["A string key"], myOtherTable[2]) -- prints: A value Another value 5
</pre>


== Arrays ==
== Arrays ==


An array, or list, is a name given to a table wereas all the keys are whole numbers (e.g. 1, 2, 3, 4...). This is very useful for creating lists of things, such as a list of people who can use a tool.
An array, or list, is a name given to a table wereas all the keys are whole numbers (e.g. 1, 2, 3, 4...). This is very useful for creating lists of things, such as a list of players with special permissions. You would not need to use a string-type key because there is no reason to - you're simply storing a numerical list of names.


When we are creating arrays, we can miss out the <code>["key"] =</code> part, and just write the values separated by commas, and Lua will automatically use the numbers 1, 2, 3, 4, 5... as the keys:
Arrays are created the same way as tables, however you can leave-out the <code>["key"] = ...</code> part, and just write the values separated by commas, and Lua will automatically associate the numbers 1, 2, 3, 4, 5... as keys to the values in the order they are given:


<pre>myArray = {"First value", "Second value", "Third value"}
<pre>myArray = {"First value", "Second value", "Third value"}
Line 67: Line 82:
</pre>
</pre>


We can get the number of values in an array (but ''not'' a normal table, only number keys are counted) by using the '''#''' operator:
You can get the amount of number keys by using the '''#''' operator:


<pre>print(#myArray) -- prints: 3</pre>
<pre>print(#myArray) -- prints: 3</pre>
Line 75: Line 90:
'''Note''': Normally, [[nil]] should not be used as a value in an array. # and Lua's table manipulation functions use nil to tell where an array ends. Putting them in the middle of your table may make Lua think the array ends there.
'''Note''': Normally, [[nil]] should not be used as a value in an array. # and Lua's table manipulation functions use nil to tell where an array ends. Putting them in the middle of your table may make Lua think the array ends there.


== Loops through tables ==
== Iteration through tables ==


We can use the [[Function_Dump/Core_Functions#pairs_.28t.29|pairs]] and [[Function_Dump/Core_Functions#ipairs_.28t.29|ipairs]] functions to write a loop that goes through every value in an array:
''Iteration'' is the repetition of an action. In this case, you are iterating through the values in a table by taking each value and doing something with it. For-loops (and sometimes while-loops) are used to iterate with tables. You can use the [[Function_Dump/Core_Functions#pairs_.28t.29|pairs]] (or [[Function_Dump/Core_Functions#ipairs_.28t.29|ipairs]] if you only want to iterate over the number keys) function to write a for-loop that goes through every value in a table with the value's key.


<pre>for key, value in pairs(myOtherTable) do
<pre>for key, value in pairs(myOtherTable) do
Line 87: Line 102:
A string key = Another value
A string key = Another value
2 = 5</pre>
2 = 5</pre>
<pre>for key, value in ipairs(myArray) do
    print(key, "=", value)
end
Outputs:
1 = First value
2 = Second value
3 = Third value</pre>
The difference between pairs and ipairs is that ipairs is designed for arrays - it only goes through the keys 1, 2, 3... until it finds a nil value. pairs goes through all the keys, but might not go through them in a set order.


== Pass by reference ==
== Pass by reference ==


An important thing to understand when setting more than one variable to the same table is that tables are ''passed by reference''. This means that the variable doesn't directly contain the table itself, but that it holds a ''reference'' to it. This means that when more than one variable is set to a table, the variables ''don't'' each have a copy of the table, they refer to the same table, so any changes will be noticed by ''both'' variables:
An important thing to understand when setting more than one variable to the same table is that tables are ''passed by reference''. This means that the variable doesn't directly contain the table itself, but that it holds a ''reference'' (or pointer) to it. This means that when more than one variable is set to a table, the variables ''do not'' each have a copy of the table, they refer to the same table, so any changes will be noticed by ''both'' variables:


<pre>var1 = {}
<pre>var1 = {}
var2 = var1
var2 = var1
var2["key"] = "value"
var2["key"] = "value"
print(var1["key"]) -- prints "value"!
print(var1["key"]) -- prints "value" because var2 had pointed to var1's value (the table)
</pre>
</pre>


Line 112: Line 116:


[[Metatables]]
[[Metatables]]
[http://www.lua.org/pil/2.5.html 2.5 - Tables]
[http://www.lua.org/pil/2.5.html 2.5 - Tables]
[http://www.lua.org/pil/2.5.html 3.6 - Table Constructors]
[http://www.lua.org/pil/2.5.html 3.6 - Table Constructors]
[http://www.lua.org/pil/11.2.html 11.2 - Matrices and Multi-Dimensional Arrays]
[http://www.lua.org/pil/11.2.html 11.2 - Matrices and Multi-Dimensional Arrays]
[[Category:Data Types]]
[[Category:Data Types]]

Revision as of 00:23, 12 May 2011

A table is a data type in Lua that is a useful way to store multiple values. It is called a table because it acts like a grid with two columns:

Key Value
   

The key column is used to find a row in the table, and the value is the value that is stored in that row. Both the key and value can be any Lua value (numbers, strings, Parts etc., and even other tables) except nil. Lua tables do not have to use either numbers, strings or tables as keys. Any combination of key types can be used.

The # operator will return the amount of keys that are numbers.

Creating a table

To create a table we use a pair of curly brackets ({}). We can then store the table in a variable:

myTable = {}

When you use curly brackets to define a table, this is called a table literal, which means you're defining a table right in your code. You're literally defining a table!

Indexing a table

Getting values into and out of a table is called indexing. An index in a table is like a row in the table model above. To index something in a table, you first need the key for the index you want to get or change the value in. You put the key in square brackets ([]) after the table that that is to be looked in. For example, to get or change the index with the key 1 in the table myTable, we write myTable[1]. You can then use this exactly like a variable or value: it can be used, or set to a different value. For example, to store the string "A value" in myTable in the row with the key 1, we would write:

myTable = {}
myTable[1] = "A value"

myTable[1] can now be used in other places. For example, the print function:

print(myTable[1]) -- prints: A value

If there is already an index in the table with the key that is being set, the old value will be replaced with the new one:

myTable[1] = "A new value"
print(myTable[1]) -- prints: A new value (as apposed to "A value")

If there isn't a row with the key we're using when we try to get a value, it will return nil:

print(myTable[2]) -- prints: nil

More on table literals

Keys can be added to the table while we are creating a table in a very similar way to indexing. Inside the curly brackets, we can put lines that are very similar to indexing, but without the name of the table, and separated by commas (,) or semicolons (;).

myOtherTable = {
    [1] = "A value",
    ["A string key"] = "Another value",
    [2] = 5
}

print(myOtherTable[1], myOtherTable["A string key"], myOtherTable[2]) -- prints: A value Another value 5

The commas and semicolons are are important! If they are not there, Lua will give an error message saying it expects the closing curly bracket (}) at the line where the next value appears.

If you are defining a key that is a string, you may simply state the string without square brackets nor quotes, so long as they follow the naming guidelines of Lua:

myOtherTable = {
    apple = "red",
    orange = "orange",
    banana = "yellow"
}

print(myOtherTable[1], myOtherTable["A string key"], myOtherTable[2]) -- prints: A value Another value 5

Arrays

An array, or list, is a name given to a table wereas all the keys are whole numbers (e.g. 1, 2, 3, 4...). This is very useful for creating lists of things, such as a list of players with special permissions. You would not need to use a string-type key because there is no reason to - you're simply storing a numerical list of names.

Arrays are created the same way as tables, however you can leave-out the ["key"] = ... part, and just write the values separated by commas, and Lua will automatically associate the numbers 1, 2, 3, 4, 5... as keys to the values in the order they are given:

myArray = {"First value", "Second value", "Third value"}
print(myArray[1]) -- prints: First value
print(myArray[2]) -- prints: Second value
print(myArray[3]) -- prints: Third value

You can get the amount of number keys by using the # operator:

print(#myArray) -- prints: 3

Lua's table manipulation functions allow you to easily do things such as add and remove values from an array.

Note: Normally, nil should not be used as a value in an array. # and Lua's table manipulation functions use nil to tell where an array ends. Putting them in the middle of your table may make Lua think the array ends there.

Iteration through tables

Iteration is the repetition of an action. In this case, you are iterating through the values in a table by taking each value and doing something with it. For-loops (and sometimes while-loops) are used to iterate with tables. You can use the pairs (or ipairs if you only want to iterate over the number keys) function to write a for-loop that goes through every value in a table with the value's key.

for key, value in pairs(myOtherTable) do
    print(key, "=", value)
end

Outputs:
1 = A value
A string key = Another value
2 = 5

Pass by reference

An important thing to understand when setting more than one variable to the same table is that tables are passed by reference. This means that the variable doesn't directly contain the table itself, but that it holds a reference (or pointer) to it. This means that when more than one variable is set to a table, the variables do not each have a copy of the table, they refer to the same table, so any changes will be noticed by both variables:

var1 = {}
var2 = var1
var2["key"] = "value"
print(var1["key"]) -- prints "value" because var2 had pointed to var1's value (the table)

See Also

Metatables 2.5 - Tables 3.6 - Table Constructors 11.2 - Matrices and Multi-Dimensional Arrays