Nested Tables and Structured Data
Build nested structures and access deep fields.
Nested Table Basics
Tables can contain other tables as values, creating arbitrarily deep structures. Access nested fields by chaining dots or brackets. Missing intermediate tables cause errors — always ensure parent tables exist before accessing deep fields.
local company = {
name = "CoddyKit",
address = {
city = "Istanbul",
country = "Turkey",
zip = "34000"
},
employees = 25
}
print(company.name) -- CoddyKit
print(company.address.city) -- Istanbul
print(company["address"]["zip"]) -- 34000Safe Deep Access
Accessing a field on a nil value crashes with "attempt to index a nil value". Guard against this with the and short-circuit: t and t.a and t.a.b. Some codebases define a get(t, ...) helper that safely traverses a chain of keys.
local function get(t, ...)
local cur = t
for _, key in ipairs({...}) do
if type(cur) ~= "table" then return nil end
cur = cur[key]
end
return cur
end
local data = {user = {profile = {age = 30}}}
print(get(data, "user", "profile", "age")) -- 30
print(get(data, "user", "missing", "field")) -- nilAll lessons in this course
- Tables as Arrays
- Tables as Dictionaries
- Iterating Tables with pairs and ipairs
- Nested Tables and Structured Data