Tables
In the context of Luau and Roblox, tables are a data structure that can store multiple values of any type that isn’t nil
, including booleans, numbers, strings, functions, and other tables.
Syntax
The syntax for an empty table is:
local table = {}
Tables can be defined using curly braces ({}
). The local
keyword is primarily used to declare local variables. It is not used specifically for instantiating tables. In order to instantiate a table with elements the syntax will look something like this:
local table = {"amy", "john", "bob"}
The above example is instantiated like an array, but as mentioned above, table data types are capable of storing any form of data other than nil
. Here is another example:
local profile = {"john", 24, "Atlanta", false}
Not only can tables be used as arrays, but you can even use them as dictionaries. Here is an example of a table in the form of a dictionary with an array data type included:
local profile = {username = "john_doe",level = 12,experience = 500,items = {"sword", "shield", "knife", "helmet"},}
Accessing Items
If a given table is set up like an array, an important thing to note is that the index begins at 1
rather than at 0
as it is for other languages. Let’s use this table as an example:
items = {"sword", "shield", "knife", "helmet"}
To print the first item of the table to the console, the call will look like this:
print(items[1])
Calling items from a table when it’s formatted like a dictionary is a little different. The value of items can be obtained by the keys. Below is an example of how to obtain the username
value from the profile
table.
-- Creating the profile tablelocal profile = {username = "john_doe",level = 12,experience = 500,items = {"sword", "shield", "knife", "helmet"},}-- Printing the username in the tableprint(profile.username)
Table Functions
The following functions are used to work with tables:
Tables
- .create()
- Returns a new table with a specified value repeated a given number of times.
- clear()
- Removes all elements from a table.
- Find()
- Searches for the first occurrence of a specified value within a table.
- foreach()
- Iterates through the elements of a provided table or collection, using a specified callback function to perform operations on each element.
- freeze()
- Makes a given table read-only.
- getn()
- Returns the number of elements in the table passed.
- isfrozen()
- Returns a boolean based on whether the table is in read-only mode or not.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.