Tables as Sequences & 1-Based Indexing

Tables as Sequences & 1-Based Indexing in Lua: In Lua, there are no separate classes for Arrays, Lists, Sets, or Maps.

In Lua, there are no separate classes for Arrays, Lists, Sets, or Maps. The Table is the sole data structuring mechanism in the entire language.

When a table uses contiguous positive integer keys starting at 1, it is considered a Sequence (or Array).


Why 1-Based Indexing?

Unlike C, Java, or Python which index from 0, Lua indices start at 1.

Lua was created for non-computer scientists (engineers and geologists at Petrobras) whose mathematical models index sequences as first, second, third ($x_1, x_2, x_3$). Starting at 1 represents natural mathematical cardinality.

local inventory = {"Broadsword", "Elixir", "Dragon Scale"}

print(inventory[1]) -- Broadsword (First item)
print(inventory[2]) -- Elixir
print(inventory[3]) -- Dragon Scale
print(inventory[0]) -- nil (Not an array index!)

The Length Operator (#) and Border Semantics

The length operator #t returns the size of a sequential table.

local weapons = {"Dagger", "Bow", "Staff"}
print(#weapons) -- Output: 3

-- Appending to the end of an array
weapons[#weapons + 1] = "Crossbow"
print(#weapons) -- Output: 4

CRITICAL PRODUCTION PITFALL: The Nil Hole Trap In Lua, a sequence is defined as a table where keys $1..n$ are non-nil. If you insert a nil in the middle of a list (creating a "hole"), the length operator # has undefined behavior according to the Lua specification! It may return the index before the hole, or the index after the hole: ``lua local brokenList = {"A", "B", nil, "D"} -- NEVER rely on #brokenList when gaps are present! ``


The Standard table Library for Sequences

local scores = {10, 45, 90, 20}

-- Insert at specific index (table.insert(t, [pos,] value))
table.insert(scores, 2, 999) -- Inserts 999 at index 2, shifting others right

-- Remove from end (returns removed element)
local last = table.remove(scores)

-- Sorting in place (table.sort(t [, comp]))
table.sort(scores, function(a, b)
    return a > b -- Descending order
end)

-- Concatenating strings into a single delimited string
local str = table.concat(scores, ", ")
print("Sorted scores: " .. str)

Iterating Sequences with ipairs

ipairs iterates strictly through contiguous integer keys starting at 1. It stops the instant it encounters a nil value:

local party = {"Fighter", "Mage", "Rogue"}

for rank, class in ipairs(party) do
    print(string.format("Rank #%d: %s", rank, class))
end

Exercises

  1. Create a function that safely removes all nil holes from an array table, producing a compact sequence.
  2. Implement a custom binary search algorithm on a sorted Lua array table.
  3. Compare the performance of table.insert(t, val) versus t[#t + 1] = val.