Learn Lua in Neovim: Iterating Tables — pairs, ipairs, Gap Behavior & Word Counter | Episode 20
Video: Learn Lua in Neovim: Iterating Tables — pairs, ipairs, Gap Behavior & Word Counter | Episode 20 by Taught by Celeste AI - AI Coding Coach
Watch full page →Learn Lua in Neovim: Iterating Tables — pairs, ipairs, Gap Behavior & Word Counter
In Lua, tables are versatile data structures that can be iterated using two primary functions: ipairs and pairs. This tutorial explains how ipairs iterates over array-like tables in order, stopping at the first nil gap, while pairs visits all keys in any order, making it ideal for dictionaries. We also demonstrate these concepts by building a word frequency counter that uses pairs to tally occurrences.
Code
-- Example table with array-like structure
local fruits = { "apple", "banana", "cherry", nil, "date" }
print("Using ipairs (stops at first nil gap):")
for i, fruit in ipairs(fruits) do
print(i, fruit)
end
-- Output:
-- 1 apple
-- 2 banana
-- 3 cherry
-- Note: iteration stops before "date" because of the nil gap at index 4
print("\nUsing pairs (visits all keys in any order):")
for key, value in pairs(fruits) do
print(key, value)
end
-- Output includes all keys, including index 5 with "date"
-- Word frequency counter example
local text = "hello world hello lua lua lua world"
local word_freq = {}
for word in text:gmatch("%w+") do
-- Increment count for each word, or initialize to 1
word_freq[word] = (word_freq[word] or 0) + 1
end
print("\nWord frequency count:")
for word, count in pairs(word_freq) do
print(word, count)
end
-- Sample output:
-- hello 2
-- world 2
-- lua 3
Key Points
ipairsiterates over array elements in order starting from index 1 and stops at the first nil value.pairsiterates over all keys in a table regardless of order or gaps, suitable for dictionaries.- Tables with gaps (nil values between elements) cause
ipairsto stop early, butpairsstill visits all entries. - Use
ipairswhen order matters and the table is a sequence; usepairsfor general key-value iteration. - Building a word frequency counter with
pairsdemonstrates practical use of table iteration for aggregating data.