← Back to Lua Course | Chapter 4: Tables | Lesson 2 of 7

Arrays and the length operator

Lua arrays start at index 1, and # tells you how many items a sequence holds.

Arrays and the length operator

A table with keys 1 to n is called a sequence. The length operator # returns the number of items in a sequence, which makes t[#t + 1] a way to append. If the table has holes, the result of # is not reliable, so avoid nil inside arrays.

Note: Use table.pack or an explicit count field when a list may contain nil values.

Example: Arrays and the length operator

lua
local fruits = {"apple", "banana", "cherry"}
print(#fruits, fruits[1], fruits[#fruits])
fruits[#fruits + 1] = "date"
print(#fruits)
print(fruits[0], fruits[10])
fruits[#fruits] = nil
print(#fruits)

-- Output:
-- 3	apple	cherry
-- 4
-- nil	nil
-- 3
Common Mistakes
  1. Starting arrays at 0
  2. Trusting # on an array containing nil holes
  3. Assigning nil to remove an element from the middle and breaking the sequence
Chapter Summary
  • Arrays start at 1
  • #t gives the length of a sequence
  • t[#t+1] appends
  • Holes make # unreliable

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.