Transfer practice · Sum dictionary values such as {wood=3,stone=2}. Do not rely on array length or ordered numeric keys.
v3 · Activity 1 of 1 · iteration · ipairs · pairs · 10 min Runs here
Use a familiar idea in a different task. Read the changed requirement before running.
Sum dictionary values such as {wood=3,stone=2}. Do not rely on array length or ordered numeric keys.
Interface: totalQuantity(items:{{quantity:number}}) -> number
| Input | Expected |
|---|---|
Named materials{ wood = 3, stone = 2 } | 5 |
No materials{} | 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.