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])
endAll lessons in this course
- Arrays as Tables
- Adding and Removing Items
- Iterating with ipairs
- Length and Sorting