Lua Tables
Use one table type as both an array and a record.
On this page
Lua basics.
- Use one table type as both an array and a record.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
Table is Lua's only data structure. With values in braces it acts as an array, and by convention the first index is 1, not 0. table.insert adds to the end and the # operator gives the length.
With names it acts as a record: person.name is shorthand for person["name"]. The concatenation operator .. joins values into a string, and numbers are converted automatically.
Code example
local scores = {82, 91, 76}
table.insert(scores, 95)
print(#scores .. " " .. scores[1])
local person = {name = "Ada", age = 36}
person.age = person.age + 1
print(person.name .. " " .. person.age)4 82 Ada 37
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
local scores = {82, 91, 76}table.insert(scores, 95)print(#scores .. " " .. scores[1])local person = {name = "Ada", age = 36}person.age = person.age + 1print(person.name .. " " .. person.age)Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| An array-style table; the first element is scores[1]. | scores = {82, 91, 76} | — | |
| Append at the end. | scores = {82, 91, 76, 95} | — | |
| Length 4 and first element 82. | scores = {82, 91, 76, 95} | 4 82 | |
| Update a field. | person.age = 37 | 4 82 | |
| Join the name and age. | person.age = 37 | 4 82 Ada 37 |
Behind the scenes
How Lua processes this code
The Lua interpreter executes the chunk and resolves local values as it runs.
Cost and common mistakes
Index access is O(1); table.insert at the end is amortized O(1).
- Lua indexes start at 1, so scores[0] is nil.
- A missing key returns nil rather than an error.
Try it yourself
What does scores[#scores] return after the insert?
Reveal answer and reasoning
The last element, 95.