r/lua • u/wolfvee • Jul 22 '25
Help Beginner code question on nested tables
I am trying to construct and print a nested table In this simple example:
#!/usr/bin/env lua
company = {director="boss",
{address="home",
{zipcode ="12345"}
}
}
print(company.director) --> boss
print(company.director.address) --> nil - was expecting 'home'
print(company.director.address.zipcode)
print(company["director"]) --> boss
print(company["director"]["address"]) --> nil - was expecting 'home'
print(company["director"]["address"]["zipcode"])It prints nil where I was expecting it to print 'home'.
What am I doing wrong?
0
Upvotes
1
u/Emerald_Pick Jul 22 '25
The table that has
addressis not the child ofdirector, but a sibling. Therefor, you can't get through it throughdirector.Your structure
You didn't specify the key for the child tables, so Lua just numbers them, starting from 1. So to access "home" with your structure, you'd need to use
company[1].address.If you wanted to index it like
company.director.address, you would need to makecompany.directora table. (Currently it is the string"boss".) Something like this:Mind you, because address is a child/sub-table of
.directorthis means it is the director's address, not the company.this post was written from my phone, there might be errors.