← Back to journey

Total the inventory quantities

v6 · Activity 3 of 5 · iteration · ipairs · pairs · 10 min Runs here

Chapter outline
Loading draft…
One step at a time

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.

Your task

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

InputExpected
Several items{ { quantity = 2 }, { quantity = 4 }, { quantity = 1 } }7
Empty inventory{}0
Syntax in this activity

New syntax: ipairs(), pairs(), for key, value in iterator do

Earlier ideas used here
  • numeric-for
  • dictionaries
  • assignment
What this exercise checks

Actual returned results for every test input · the stated behavior · extra output allowed.

Successful execution is required. A compile error, runtime error or execution limit never completes this task.

Whitespace, matching single or double quotes, and different variable names are allowed. Output-only tasks accept any valid Luau solution meeting the displayed result and value types. Construct tasks use the stated straight-line form.

Explain this code

Select a word or symbol in this authored example. Your editor draft stays unchanged.

 counts  , , 
 total  
 _, count in counts 
    total  total  count

 total
Choose a highlighted part to see what it means.
Free experiment

This 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.

Luau keyword highlighting · Ctrl/⌘ + Enter: Run · Esc: leave editor
Experiment Output

Your output will appear here.

Your goal

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.

Run code to see what happens. Check solution to test the activity.

Reset starter

Replace this code with the starter? Download your draft to keep a copy.

Code

Luau
Luau keyword highlighting · Ctrl/⌘ + Enter: Run · Esc: leave editor

Your output will appear here.

Ready