0Pricing
Lua Academy · Lesson

Length and Sorting

Count and sort sequences.

The Length Operator

The # operator returns the number of items in a sequence.

For a clean 1-based table with three elements, #t is 3. The last item lives at index #t.

local list = {"a", "b", "c"}
print(#list)
print(list[#list])

Length in a Loop

Use #t as the upper bound of a numeric for loop to visit every index.

Since sequences are 1-based, the range is 1, #t.

local nums = {10, 20, 30, 40}
for i = 1, #nums do
  print(i, nums[i])
end

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