Tables: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>NXTBoy
So it kinda doesn't make sense as a whole any more. I might come back to it. Revert as required.
m Text replacement - "<SyntaxHighlight code="lua">" to "<syntaxhighlight lang="lua">"
 
(28 intermediate revisions by 7 users not shown)
Line 1: Line 1:
A '''table''' is a data type in Lua that is a useful way to store multiple values, including numbers, strings, functions, more tables, and much more. It is called a table because it acts like a grid with two columns:


{| border="1"
A {{type|table}} is a data type in Lua that is useful to store multiple values, including {{type|number|numbers}}, {{type|string|strings}}, {{type|function|functions}}, more {{type|table|tables}}, and much more. It is called a table because it acts like a grid with two columns:
 
{| class="wikitable"
! Key  !!Value
! Key  !!Value
|-
|-
Line 7: Line 8:
|}
|}


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 ''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 ({{type|number|numbers}}, {{type|string|strings}}, {{type|instance=Part|Parts}} etc., and even other tables) except {{nil}}. Lua tables do not have to use either {{type|number|numbers}}, {{type|string|strings}} or {{type|table|tables}} as keys. Any combination of key types can be used.


The <code>#</code> operator will return the amount of keys that are numbers.
Another way to describe it is that by inputting the key, you receive the value.


__TOC__
The # operator will return the amount of keys that are {{type|number|numbers}}.


== Arrays ==
== Arrays ==
Line 19: Line 20:
===Creating arrays===
===Creating arrays===


Arrays are created with a pair of braces (<code>{</code> and <code>}</code>, containing the values to store in the array separated by commas (<code>,</code>) or semicolons (<code>;</code>). The values can be of any type
Arrays are created with a pair of braces ({ and }, containing the values to store in the array separated by commas (,) or semicolons (;). The values can be of any type
 
<syntaxhighlight lang="lua">
local myArray = {"A string", 3.14159, workspace.Part}
local myArray = {"A string", 3.14159, Workspace.Part}
local myEmptyArray = {}
local myEmptyArray = {}
</syntaxhighlight>


=== Reading from and writing to arrays ===
=== Reading from and writing to arrays ===


To read from an array, add a pair of brackets (<code>[</code> and <code>]</code>) after the array, and put the number of the element you want inside it. The first element in the array is number 1
To read from an array, add a pair of brackets ([ and ]) after the array, and put the number of the element you want inside it. The first element in the array is number 1
 
<syntaxhighlight lang="lua">
print(myArray[1])              -- prints: A string
print(myArray[1])              --> A string
print(myArray[2])              -- prints: 3.14159
print(myArray[2])              --> 3.14159
print(myArray[3]:GetFullName()) -- prints: Workspace.Part
print(myArray[3]:GetFullName()) --> Workspace.Part
 
myArray[2] = "Pi"


print(myArray[2])              -- prints: Pi
myArray[2] = "Pi"
print(myArray[2])              --> Pi
</syntaxhighlight>


===More information===
===More information===


You can get the amount of number keys by using the '''#''' operator:
You can get the length of the array with the # operator:
 
<syntaxhighlight lang="lua">
print(#myArray)      -- prints: 3
print(#myArray)      --> 3
print(#myEmptyArray ) -- prints: 0
print(#myEmptyArray ) --> 0
 
</syntaxhighlight>


Lua's [[Function_Dump/Table_Manipulation|table manipulation]] functions allow you to easily do things such as add and remove values from an array.
Lua's [[Function_Dump/Table_Manipulation|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.


== Dictionaries ==
== Dictionaries ==
Line 53: Line 53:
=== Creating a dictionary ===
=== Creating a dictionary ===
Once again, dictionaries are created with braces
Once again, dictionaries are created with braces
 
<syntaxhighlight lang="lua">
local myDictionary = {
local myDictionary = {
    ["Roblox"] = "A massively multiplayer online game",
["Roblox"] = "A massively multiplayer online game",
    ["Wiki"] = "A Web site developed collaboratively by a community of users",
["Wiki"] = "A Web site developed collaboratively by a community of users",
    ["Lua"] = "A lightweight multi-paradigm programming language"
["Lua"] = "A lightweight multi-paradigm programming language"
}
}
</syntaxhighlight>


Like arrays, dictionaries are not restricted to strings. Both the keys and the values can be of any type.
Like arrays, dictionaries are not restricted to strings. Both the keys and the values can be of any type.


local playerScores = {
<syntaxhighlight lang="lua">
    [game.Players.Telamon] = "Over 9000!",
local playerScores = {
    [game.Players.ROBLOX] = 1337,
[game.Players.Telamon] = "Over 9000!",
    [game.Players.Sorcus] = Enum.DialogTone.Enemy
[game.Players.ROBLOX] = 1337,
}
[game.Players.Sorcus] = Enum.DialogTone.Enemy
}
</syntaxhighlight>


====Shorthand for string keys====
====Shorthand for string keys====


If a key in a dictionary is a string, and a valid lua [[identifier]], the quotes and brackets can be omitted:
If a key in a dictionary is a string, and a valid Lua identifier (that is, it can be used as [[Variables#Names|the name of a variable]]), the quotes and brackets can be omitted:


local myDictionary = {
<syntaxhighlight lang="lua">
    Roblox = "A massively multiplayer online game",
local myDictionary = {
    Wiki = "A Web site developed collaboratively by a community of users",
Roblox = "A massively multiplayer online game",
    Lua = "A lightweight multi-paradigm programming language"
Wiki = "A Web site developed collaboratively by a community of users",
}
Lua = "A lightweight multi-paradigm programming language"
}
</syntaxhighlight>


===Indexing a dictionary ===
===Indexing a dictionary ===


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 <code>myTable</code>, we write <code>myTable[1]</code>. 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 <code>myTable</code> in the row with the key 1, we would write:
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:


<pre>myTable = {}
<syntaxhighlight lang="lua">
myTable[1] = "A value"</pre>
myTable = {}
myTable[1] = "A value"
</syntaxhighlight>


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


<pre>print(myTable[1]) -- prints: A value</pre>
<syntaxhighlight lang="lua">print(myTable[1]) --> A value</syntaxhighlight>


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:
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:


<pre>myTable[1] = "A new value"
<syntaxhighlight lang="lua">
print(myTable[1]) -- prints: A new value (as apposed to "A value")</pre>
myTable[1] = "A new value"
print(myTable[1]) --> A new value (as apposed to "A value")
</syntaxhighlight>


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


<pre>print(myTable[2]) -- prints: nil</pre>
<syntaxhighlight lang="lua">print(myTable[2]) --> nil</syntaxhighlight>


== Iteration through tables ==
== Iteration through tables ==
Line 102: Line 111:
''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.
''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
<syntaxhighlight lang="lua">
    print(key, "=", value)
for key, value in pairs(myOtherTable) do
print(key, "=", value)
end
end


Outputs:
--[[
Output:
1 = A value
1 = A value
A string key = Another value
A string key = Another value
2 = 5</pre>
2 = 5
]]
</syntaxhighlight>


== Pass by reference ==
== Pass by reference ==
Line 115: Line 128:
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:
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 = {}
<syntaxhighlight lang="lua">
var1 = {}
var2 = var1
var2 = var1
var2["key"] = "value"
var2["key"] = "value"
print(var1["key"]) -- prints "value" because var2 had pointed to var1's value (the table)
print(var1["key"]) -- prints "value" because var2 had pointed to var1's value (the table)
</pre>
</syntaxhighlight>


== See Also ==
== See also ==


* [[Metatables]]
* [[Metatables]]
* [http://www.lua.org/pil/2.5.html 2.5 - Tables]
* From Programming in Lua:
* [http://www.lua.org/pil/2.5.html 3.6 - Table Constructors]
** [http://www.lua.org/pil/2.5.html 2.5 - Tables]
* [http://www.lua.org/pil/11.2.html 11.2 - Matrices and Multi-Dimensional Arrays]
** [http://www.lua.org/pil/2.5.html 3.6 - Table Constructors]
* [http://lua-users.org/wiki/TablesTutorial Tables Tutorial]
** [http://www.lua.org/pil/11.2.html 11.2 - Matrices and Multi-Dimensional Arrays]
[[Category:Data Types]]
* [http://lua-users.org/wiki/TablesTutorial Tables Tutorial] on Lua Users wiki
* Using Tables to create data structures:
** [[Linked lists]]
** [[Stack]]
[[Category:Data types]]

Latest revision as of 06:18, 27 April 2023

A table is a data type in Lua that is useful to store multiple values, including numbers, strings, functions, more tables, and much more. 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.

Another way to describe it is that by inputting the key, you receive the value.

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

Arrays

An array is a list of values, stored in order. It is a table where the keys are sequential integers starting at 1, e.g. 1, 2, 3, 4. Arrays are useful for creating lists of things, such as a list of players with special permissions.

Creating arrays

Arrays are created with a pair of braces ({ and }, containing the values to store in the array separated by commas (,) or semicolons (;). The values can be of any type

local myArray = {"A string", 3.14159, Workspace.Part}
local myEmptyArray = {}

Reading from and writing to arrays

To read from an array, add a pair of brackets ([ and ]) after the array, and put the number of the element you want inside it. The first element in the array is number 1

print(myArray[1])               --> A string
print(myArray[2])               --> 3.14159
print(myArray[3]:GetFullName()) --> Workspace.Part

myArray[2] = "Pi"
print(myArray[2])               --> Pi

More information

You can get the length of the array with the # operator:

print(#myArray)       --> 3
print(#myEmptyArray ) --> 0

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

Dictionaries

Dictionaries are an extension of arrays. While an array stores an ordered list of items, a dictionary stores a set of key/value pairs. For example, in a real dictionary, the "keys" are the words, and the "values" the definition.

Creating a dictionary

Once again, dictionaries are created with braces

local myDictionary = {
	["Roblox"] = "A massively multiplayer online game",
	["Wiki"] = "A Web site developed collaboratively by a community of users",
	["Lua"] = "A lightweight multi-paradigm programming language"
}

Like arrays, dictionaries are not restricted to strings. Both the keys and the values can be of any type.

local playerScores = {
	[game.Players.Telamon] = "Over 9000!",  
	[game.Players.ROBLOX] = 1337,
	[game.Players.Sorcus] = Enum.DialogTone.Enemy
}

Shorthand for string keys

If a key in a dictionary is a string, and a valid Lua identifier (that is, it can be used as the name of a variable), the quotes and brackets can be omitted:

local myDictionary = {
	Roblox = "A massively multiplayer online game",
	Wiki = "A Web site developed collaboratively by a community of users",
	Lua = "A lightweight multi-paradigm programming language"
}

Indexing a dictionary

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]) --> 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]) --> 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]) --> nil

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

--[[
Output:
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