v3 · Activity 3 of 5 · iteration · ipairs · pairs · 10 min Runs here
ipairs visits a dense sequence in index order. In for index, item in ipairs(items) do, the second value is the item at the current index.
pairs visits keys and values in a table without promising a sorted order. Use it for named fields when order is irrelevant.
totalQuantity(items) sums every item.quantity. The sequence is dense and each quantity is a number. Move the return out of the loop. Keep the final return shown in the starter so the checker can call or inspect your result.
Interface: totalQuantity(items:{{quantity:number}}) -> number
| Input | Expected |
|---|---|
Several items{ { quantity = 2 }, { quantity = 4 }, { quantity = 1 } } | 7 |
Empty inventory{} | 0 |
local counts = {2, 4, 1}
local total = 0
for _, count in ipairs(counts) do
total = total + count
end
return totalThe unused index is named _. The accumulator grows from 0 to 2 to 6 to 7.
New syntax: ipairs(), pairs(), for key, value in iterator do
ipairs visits a dense sequence in index order. In for index, item in ipairs(items) do, the second value is the item at the current index.
pairs visits keys and values in a table without promising a sorted order. Use it for named fields when order is irrelevant.
An accumulator begins at the neutral value, zero for addition. Update it for each item and return it only after the loop finishes.
Select a word or symbol in this authored example. Your editor draft stays unchanged.
totalQuantityitems
total 0
_, item in items
total total item.quantity
total
totalQuantityThis is a private experiment copy. It does not replace your answer or complete the activity.
These inputs apply when your scratchpad returns the function described by the activity interface.
Your output will appear here.
Replace this code with the starter? Download your draft to keep a copy.
Your output will appear here.
Sign in with RoCreators to save private progress across devices. Community verification is separate.