LUA / CHAPTER 06
Iteration and string processing
IntermediateChoose iteration rules that match sequences, maps, and text.
By the end of this chapter
- Trace numeric for loops
- Choose ipairs or pairs
- Use string functions without mutation
The idea
A numeric for loop visits a range using a specified step; its endpoint is included when the progression reaches it. ipairs visits consecutive numeric entries beginning at one and stops at the first absent entry. pairs visits table keys, but its traversal order is unspecified. Choose the iterator from the data contract instead of assuming every table behaves like an ordered list.
Strings are immutable values. Functions such as string.sub and string.upper produce results rather than editing the original string. String indices in these operations refer to bytes, so simple ASCII exercises should not be mistaken for complete Unicode text processing. When accumulating a sequence of text fragments, table.concat expresses the final join clearly. Keep filtering and formatting separate when either rule may change.
local words = {"map", "loop", "if"}
local selected = {}
for _, word in ipairs(words) do
if #word >= 3 then selected[#selected + 1] = string.upper(word) end
end
print(table.concat(selected, ","))MAP,LOOP
ipairs follows the dense sequence in order. Two ASCII words satisfy the byte-length threshold, and their uppercase copies are joined with commas.
Try it yourself
Return a comma-separated string of the first two ASCII characters of each word in a dense sequence.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING