Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 32 ยท Tables

Tables in Practice

Use Lua tables as sets, stacks, queues and matrices, and learn the difference between shallow and deep copies and why tables are references.

You now know how to create tables and use the table library. This lesson turns them into the data structures real programs need: sets, stacks, queues and matrices. Then it tackles the topic that causes the most bugs with tables: they are references, so copying one takes thought.

As before, Lua code is read-only here and the live editors are JavaScript stand-ins that mirror Lua's behavior. Check Tables as Arrays and Dictionaries and The table Library first if t[#t + 1] or table.remove look unfamiliar.

One table, five shapes

Set Keys with value true.
Stack Last in, first out.
Queue First in, first out.
Matrix Tables inside a table.

Choose the shape, then pick the keys.

1 / 2

Sets

Lua has no set type, but a table does the job: store each member as a key with the value true. Membership tests are a single lookup, and adding the same item twice changes nothing:

LUA
local seen = {}
seen["apple"] = true
seen["pear"] = true
seen["apple"] = true            -- no effect, already there

print(seen["apple"])            --> true
print(seen["kiwi"])             --> nil  (falsy: not a member)
seen["pear"] = nil              -- remove a member

Since only nil and false are falsy (see Operators and Truthiness), if seen[x] then works as a membership test. Iterating a set with pairs visits members in no guaranteed order. A handy helper turns a list into a set:

LUA
local function toSet(list)
  local set = {}
  for _, item in ipairs(list) do set[item] = true end
  return set
end
JS Stand-in: a set from a list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stacks

A stack adds and removes at the same end. In Lua that is table.insert(stack, value) to push and table.remove(stack) to pop. Both work at the end of the list, so they stay fast no matter how big the stack grows:

LUA
local stack = {}
table.insert(stack, "a")
table.insert(stack, "b")
print(table.remove(stack))      --> b
print(table.remove(stack))      --> a
print(table.remove(stack))      --> nil (empty)

Writing stack[#stack + 1] = value for a push avoids a function call, and is common in performance-minded code.

Queues

A queue adds at one end and removes from the other. Using table.remove(queue, 1) works, but it shifts every remaining item down, which gets slow for large queues. The usual fix is to keep two indexes, first and last, and never move anything:

LUA
local Queue = {first = 1, last = 0, items = {}}

function Queue.push(q, value)
  q.last = q.last + 1
  q.items[q.last] = value
end

function Queue.pop(q)
  if q.first > q.last then return nil end
  local value = q.items[q.first]
  q.items[q.first] = nil          -- let the value be garbage collected
  q.first = q.first + 1
  return value
end

Here the keys of items form a moving window, so the table is not a sequence starting at 1, and # is meaningless for it. That is fine, because the queue tracks its own bounds.

JS Stand-in: a two-index queue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Matrices and nested tables

A table can hold other tables, which gives you grids and trees. A matrix is a table of rows, where each row is a table:

LUA
local grid = {
  {1, 2, 3},
  {4, 5, 6},
}
print(grid[2][3])               --> 6   (row 2, column 3)
print(#grid, #grid[1])          --> 2   3

If you build a grid in a loop, remember to create each row as its own table. Reusing one row table makes every row the same row (see the next section).

LUA
local function newGrid(rows, cols, fill)
  local g = {}
  for r = 1, rows do
    g[r] = {}                   -- a fresh table per row
    for c = 1, cols do g[r][c] = fill end
  end
  return g
end
JS Stand-in: building a grid correctly

Press Run (or Ctrl + Enter) to see the console output here.

No output.

References, aliases and copies

A table variable holds a reference. Assigning it makes an alias, not a copy, and == compares identity:

LUA
local a = {1, 2}
local b = a
b[1] = 100
print(a[1])                     --> 100
print(a == b)                   --> true  (same table)
print({1, 2} == {1, 2})         --> false (two different tables)

To get independent data, copy it. A shallow copy creates a new outer table, but the values are copied as they are, so any nested tables are still shared:

LUA
local function shallowCopy(t)
  local copy = {}
  for k, v in pairs(t) do copy[k] = v end
  return copy
end

A deep copy recurses into nested tables so nothing is shared:

LUA
local function deepCopy(value)
  if type(value) ~= "table" then return value end
  local copy = {}
  for k, v in pairs(value) do
    copy[deepCopy(k)] = deepCopy(v)
  end
  return copy
end

This simple version breaks on tables that contain themselves (it would recurse forever), and it ignores metatables. Production code passes along a "seen" table to remember what was already copied. You will meet metatables in Metatables and Metamethods.

JS Stand-in: shallow versus deep copy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you test whether word is a member of a set stored as set[word] = true?

    A missing key reads as nil, which is falsy, so set[word] is truthy only for members. set.word would look up the literal key "word".
  2. 2. Why does a queue often use first and last indexes instead of table.remove(queue, 1)?

    Removing from the front moves every later item down. Tracking bounds avoids moving anything.
  3. 3. After local b = a where a is a table, what does b[1] = 5 do?

    Assignment copies the reference, not the table, so a and b are aliases of one table.
  4. 4. What is the weakness of a shallow copy?

    A shallow copy duplicates only the outer table. Values that are tables are the same tables in both copies.
  5. 5. What does {1, 2} == {1, 2} evaluate to in Lua?

    Tables compare by identity. Two separately created tables are different even with equal contents (unless an __eq metamethod says otherwise).

Summary

  • Sets are tables with members as keys and true as values.
  • Stacks use table.insert(t, v) and table.remove(t) at the end; queues track first and last to avoid shifting.
  • Matrices are tables of tables; create each row as a fresh table.
  • Table variables are references: = makes an alias and == compares identity.
  • A shallow copy shares nested tables; a deep copy recurses (and needs care with cycles and metatables).

Next, learn what makes tables programmable in Metatables and Metamethods.