In Lua, tables are versatile data structures that can be used as dictionaries, also known as associative arrays or hash tables. This powerful feature allows developers to store and retrieve data using key-value pairs efficiently.
To create a table that functions as a dictionary, simply use curly braces and assign key-value pairs:
local person = {
name = "John Doe",
age = 30,
occupation = "Developer"
}
In this example, we've created a table called person
with three key-value pairs.
You can access values using either dot notation or square bracket notation:
print(person.name) -- Output: John Doe
print(person["age"]) -- Output: 30
-- Modifying values
person.occupation = "Designer"
person["age"] = 31
Dot notation is typically used for keys that are valid identifiers, while square bracket notation is more flexible and can handle any type of key.
Adding new key-value pairs is straightforward:
person.email = "john@example.com"
person["phone"] = "555-1234"
To remove a key-value pair, simply assign nil
to the key:
person.phone = nil
Use the pairs()
function to iterate over all key-value pairs in a table:
for key, value in pairs(person) do
print(key .. ": " .. tostring(value))
end
nil
.
if person.email then
print("Email exists:", person.email)
else
print("Email not found")
end
Use the #
operator with caution, as it only works reliably for sequence-like tables. For dictionaries, consider using a custom function:
local function tableLength(t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
print("Number of entries:", tableLength(person))
To further enhance your understanding of Lua tables and their usage, explore these related topics:
By mastering tables as dictionaries, you'll unlock powerful data management capabilities in Lua, enabling you to create more efficient and flexible programs.