0Pricing
Lua Academy · Lesson

Adding and Removing Items

Use table.insert and remove.

Growing a Sequence

Real lists change size while a program runs. Lua gives you table.insert to append items at the end.

Because sequences are 1-based, an append after two items lands at index 3.

local list = {"a", "b"}
table.insert(list, "c")
print(list[1], list[2], list[3])

table.insert Appends

Called with two arguments, table.insert(t, value) places value at the position right after the current last index.

Each call grows the sequence by one, keeping the indices contiguous.

local q = {}
table.insert(q, "first")
table.insert(q, "second")
print(q[1], q[2])

All lessons in this course

  1. Arrays as Tables
  2. Adding and Removing Items
  3. Iterating with ipairs
  4. Length and Sorting
← Back to Lua Academy