Tables, Arrays & Dictionaries
Understanding Tables in Luau
Tables are the core data structure in Luau, serving as both arrays and dictionaries. They allow you to store collections of values and are highly flexible. In this article, we will explore how to use tables effectively, including creating arrays, dictionaries, nesting tables, and manipulating them with built-in functions.
Arrays and Numeric Keys
An array in Luau is a table where the keys are numeric. You can create an array by initializing a table with a list of values. Here's an example:
local myArray = {10, 20, 30, 40}
In this example, myArray is an array containing four numeric values. You can access these values using their indices, starting from 1:
print(myArray[1]) -- Output: 10
Dictionaries and String Keys
Dictionaries are tables that use string keys. They are useful for storing key-value pairs. Here’s how to create a dictionary:
local myDictionary = {name = "John", age = 25}
You can access the values using their keys:
print(myDictionary.name) -- Output: John
To add a new key-value pair, simply assign a value to a new key:
myDictionary.location = "New York"
Nesting Tables
Tables can be nested, allowing you to create complex data structures. For example, you can have an array of dictionaries:
local students = {
{name = "Alice", grade = 90},
{name = "Bob", grade = 85}
}
You can access nested values like this:
print(students[1].name) -- Output: Alice
Manipulating Tables: Insert and Remove
Luau provides built-in functions to manipulate tables. You can use table.insert to add elements to an array:
table.insert(myArray, 50)
This adds 50 to the end of myArray. You can also use table.remove to remove an element:
table.remove(myArray, 1) -- Removes the first element
After this operation, myArray will now start with 20.
Length Operator and Iteration
The # operator can be used to find the length of an array:
local length = #myArray
This will give you the number of elements in myArray.
To iterate over an array, you can use ipairs, which provides a simple way to access elements in order:
for index, value in ipairs(myArray) do
print(index, value)
end
For dictionaries, use pairs to iterate over key-value pairs:
for key, value in pairs(myDictionary) do
print(key, value)
end
Conclusion
Tables in Luau are versatile and powerful. Understanding how to use arrays, dictionaries, and nested tables will enhance your scripting capabilities. With functions like table.insert, table.remove, and iteration methods, you can manipulate and access data efficiently. Start experimenting with tables to fully leverage their potential in your Roblox projects!