Lua with Neovim: Tables as Dictionaries — Key-Value Pairs, Dot & Bracket Notation | Episode 19
Video: Lua with Neovim: Tables as Dictionaries — Key-Value Pairs, Dot & Bracket Notation | Episode 19 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lua with Neovim: Tables as Dictionaries — Key-Value Pairs, Dot & Bracket Notation
Lua tables are versatile structures that can act as dictionaries, storing key-value pairs rather than just arrays. In this example, we create tables using the {key = value} syntax, access and modify entries with dot and bracket notation, and delete keys by assigning nil. These techniques are essential for managing structured data in Lua scripts, especially when configuring Neovim.
Code
-- Create a table as a dictionary with key-value pairs
local person = {
name = "Alice", -- string key with string value
age = 30, -- string key with number value
city = "New York"
}
-- Access values using dot notation (only for simple string keys)
print(person.name) -- Output: Alice
-- Access values using bracket notation (works with any key)
print(person["age"]) -- Output: 30
-- Add a new key-value pair using dot notation
person.email = "alice@example.com"
-- Update an existing key
person.age = 31
-- Delete a key by assigning nil
person.city = nil
-- Access a key using a variable with bracket notation
local key = "email"
print(person[key]) -- Output: alice@example.com
-- Print the updated table keys and values
for k, v in pairs(person) do
print(k, v)
end
Key Points
- Lua tables can store key-value pairs using the {key = value} constructor syntax.
- Dot notation (t.key) is a concise way to access or assign values for simple string keys.
- Bracket notation (t["key"]) allows access with any key type, including variables or keys with special characters.
- Assigning a value to a key adds or updates it; assigning nil deletes the key from the table.
- These table operations are fundamental for configuring Neovim and managing structured data in Lua.