LUA / CHAPTER 05

Tables and sequences

Intermediate

Use one flexible data structure with clear key and sequence rules.

By the end of this chapter

  • Read and update table fields
  • Distinguish aliases from copies
  • Maintain contiguous sequence indices

The idea

A Lua table maps keys to values. A field such as item.name is convenient syntax for item["name"], while numeric keys support sequences. By convention, a sequence uses consecutive integer keys beginning at one. Store a list without holes when you need its length, table.insert, table.remove, or ipairs to behave as ordinary sequence operations. Assigning nil removes an existing key from the table.

Variables that refer to the same table share that object. Assigning one table variable to another does not copy its entries, so a mutation through either reference is visible through the other. Create a new table and copy the required entries when independent state is needed. That entry-by-entry copy is shallow: nested tables remain shared unless you deliberately copy them too.

Lua example
local scores = {3, 7, 9}
local same = scores
same[2] = 8
table.remove(scores, 1)
print(scores[1])
print(#scores)
Result
8
2

The alias updates the shared second entry. Removing the first entry shifts the remaining sequence entries down, producing a two-element sequence.

Try it yourself

Copy a dense sequence of numbers into a fresh table, then change the copy without changing the original.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does this print?
local item = {count = 2}
local other = item
other.count = 6
print(item.count)