Lua with Neovim: Nested Tables — Tables Inside Tables, Chained Access & Averages | Episode 21
Video: Lua with Neovim: Nested Tables — Tables Inside Tables, Chained Access & Averages | Episode 21 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lua with Neovim: Nested Tables — Tables Inside Tables, Chained Access & Averages
In Lua, tables can contain other tables, enabling the representation of complex, structured data. This example demonstrates nested tables for student records, accessing and modifying deeply nested values using chained dot notation, and calculating averages by iterating over an array of such nested tables.
Code
-- Define a student with nested tables for grades and address
local student = {
name = "Alice",
grades = { math = 90, science = 85, literature = 88 },
address = {
city = "Springfield",
street = "742 Evergreen Terrace"
}
}
-- Access nested values using chained dot notation
print("City:", student.address.city) -- Output: Springfield
print("Math grade:", student.grades.math) -- Output: 90
-- Modify a nested value
student.address.city = "Shelbyville"
print("New city:", student.address.city) -- Output: Shelbyville
-- Create an array (list) of student tables
local classroom = {
{
name = "Alice",
grades = { math = 90, science = 85, literature = 88 }
},
{
name = "Bob",
grades = { math = 75, science = 80, literature = 78 }
},
{
name = "Charlie",
grades = { math = 92, science = 88, literature = 95 }
}
}
-- Calculate average math grade for the classroom
local sum = 0
local count = #classroom
for i = 1, count do
sum = sum + classroom[i].grades.math
end
local average = sum / count
-- Format output to 2 decimal places
print(string.format("Average math grade: %.2f", average)) -- Output: Average math grade: 85.67
Key Points
- Tables can be nested inside other tables to represent complex data structures like student records.
- Chained dot notation (e.g., student.address.city) allows easy access and modification of deeply nested values.
- Arrays of tables enable storing multiple structured records, such as a classroom of students.
- Looping through arrays of nested tables lets you compute aggregates like averages efficiently.
- string.format is useful for formatting numerical output with precise decimal rounding.