Arrays and the length operator
Lua arrays start at index 1, and # tells you how many items a sequence holds.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Starting arrays at 0
- Trusting # on an array containing nil holes
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: