0Pricing
Lua Academy · Lesson

Tables as Arrays

Create and manipulate 1-indexed arrays with table.insert and table.remove.

Tables as Arrays is a free Lua Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1-Indexed Arrays

Lua arrays are tables with consecutive integer keys starting at 1. This differs from most languages which start at 0. The convention is universal in Lua — all standard library functions assume 1-based indexing. Out-of-bound access returns nil, not an error.

local colors = {"red", "green", "blue"}
print(colors[1])   -- red
print(colors[2])   -- green
print(colors[3])   -- blue
print(colors[0])   -- nil (no index 0)
print(#colors)     -- 3 (length operator)

table.insert and table.remove

table.insert(t, val) appends to the end. table.insert(t, pos, val) inserts at a position, shifting elements right. table.remove(t, pos) removes the element at pos (default: last), shifting elements left, and returns the removed value.

local stack = {}
table.insert(stack, "first")
table.insert(stack, "second")
table.insert(stack, "third")
print(#stack)          -- 3

table.insert(stack, 2, "inserted")
print(stack[2])        -- inserted

local removed = table.remove(stack, 1)
print(removed)         -- first
print(stack[1])        -- inserted

Stack with Tables

A Lua table makes a perfect stack. Use table.insert to push and table.remove to pop. Both operations work from the end of the table by default, giving O(1) amortized time.

local stack = {}

-- Push
table.insert(stack, 10)
table.insert(stack, 20)
table.insert(stack, 30)

-- Pop
print(table.remove(stack))  -- 30
print(table.remove(stack))  -- 20
print(#stack)               -- 1

Queue with Tables

A queue (FIFO) can be implemented with a table, but table.remove(t, 1) is O(n) because it shifts all elements. For high-performance queues, use two pointers (head and tail indices) to avoid shifting.

local head, tail = 1, 0
local queue = {}

local function enqueue(v)
  tail = tail + 1
  queue[tail] = v
end

local function dequeue()
  if head > tail then return nil end
  local v = queue[head]
  queue[head] = nil
  head = head + 1
  return v
end

enqueue("a"); enqueue("b"); enqueue("c")
print(dequeue())  -- a
print(dequeue())  -- b

The # Length Operator

The # operator returns the "border" of a table: an index i such that t[i] ~= nil and t[i+1] == nil. For sequences without holes, this equals the array length. With holes (nil in the middle), # gives undefined results — use table.pack or track length manually.

local t = {10, 20, 30, 40, 50}
print(#t)   -- 5

-- Safe for dense arrays
for i = #t, 1, -1 do
  io.write(t[i] .. " ")
end
print()  -- 50 40 30 20 10

Slicing Arrays

Lua has no built-in slice, but you can extract a sub-array with table.move (Lua 5.3+) or a manual loop. table.move(a1, f, e, t, a2) copies elements from a1[f..e] into a2 starting at position t.

local src = {10,20,30,40,50,60}

-- Manual slice
local function slice(t, from, to)
  local result = {}
  for i = from, to do
    result[#result+1] = t[i]
  end
  return result
end

local sub = slice(src, 2, 4)
print(sub[1], sub[2], sub[3])  -- 20  30  40

Reverse an Array

Reverse a table in-place by swapping elements from both ends toward the middle. This is a classic algorithm that works on any Lua array without extra memory.

local function reverse(t)
  local n = #t
  for i = 1, math.floor(n / 2) do
    t[i], t[n - i + 1] = t[n - i + 1], t[i]
  end
end

local arr = {1, 2, 3, 4, 5}
reverse(arr)
for _, v in ipairs(arr) do
  io.write(v .. " ")
end
print()  -- 5 4 3 2 1

Concatenating Arrays

To merge two arrays into one, loop over the second and append its elements. table.move does this efficiently in Lua 5.3+. The result is a new table containing all elements from both arrays in order.

local function concat(a, b)
  local result = {}
  for _, v in ipairs(a) do result[#result+1] = v end
  for _, v in ipairs(b) do result[#result+1] = v end
  return result
end

local merged = concat({1,2,3}, {4,5,6})
for i, v in ipairs(merged) do
  io.write(v .. " ")
end
print()  -- 1 2 3 4 5 6

Flattening Nested Arrays

Flatten a nested array recursively: if an element is a table, recurse into it; otherwise, append it to the result. This is a natural application of recursive table traversal.

local function flatten(t, result)
  result = result or {}
  for _, v in ipairs(t) do
    if type(v) == "table" then
      flatten(v, result)
    else
      result[#result+1] = v
    end
  end
  return result
end

local nested = {1, {2, 3}, {4, {5, 6}}, 7}
local flat = flatten(nested)
print(table.concat(flat, ", "))  -- 1, 2, 3, 4, 5, 6, 7

Array as Set

You can implement a set using a table where values are keys and the value is true. Set membership check is O(1). Building a set from an array deduplicates it. Convert back to array by iterating with pairs.

local function toSet(arr)
  local set = {}
  for _, v in ipairs(arr) do set[v] = true end
  return set
end

local nums = {3,1,4,1,5,9,2,6,5,3}
local set = toSet(nums)
local unique = {}
for k in pairs(set) do unique[#unique+1] = k end
table.sort(unique)
print(table.concat(unique, " "))  -- 1 2 3 4 5 6 9

Quick Check

What does table.remove(t) do when called with only one argument?

Recap: Tables as Arrays

Summary:

  • Lua arrays are 1-indexed tables
  • table.insert/table.remove for push/pop
  • #t gives length for sequences without holes
  • Stack: insert/remove from end (O(1))
  • Queue: use head+tail pointers to avoid O(n) shift
  • Use table-as-set for O(1) membership tests

Frequently asked questions

Is the “Tables as Arrays” lesson free?

Yes — the full text of “Tables as Arrays” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Tables as Arrays”?

Create and manipulate 1-indexed arrays with table.insert and table.remove. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Tables as Arrays” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Tables as Arrays
  2. Tables as Dictionaries
  3. Iterating Tables with pairs and ipairs
  4. Nested Tables and Structured Data
← Back to Lua Academy