Lesson 2 of 10

Looping over a table

Goal

ipairs for lists and pairs for dictionaries

01

Explanation

ipairs(t) walks a table as a list: it takes index 1, then 2, then 3, in order, and stops at the first nil. pairs(t), on the other hand, goes over every key, numbers and strings alike, and it's how you get at the contents of a dictionary like { hp = 100, mana = 40 }.

You can't count a dictionary's keys with #, because it measures the sequence that starts at index 1. A stats dictionary has no index 1, so you get 0. To count its keys, loop over them with pairs and add one to a counter each time.

Keep in mind that pairs guarantees no order: mana may come before hp, and the order can change from one run to the next. When you need a fixed order, as on a player's stats screen, keep that order in a separate list and loop over it with ipairs.

02

Your task

Fix countKeys(t) so it counts the keys of any table. Then write hasItem(items, name), which returns true or false depending on whether name is in the list, and orderedStats(stats, order), which returns a list of strings like "hp: 100" for the keys in order only, in that same order.

Checks

6 checks
  1. countKeys counts a dictionary's keys
  2. countKeys counts list elements and handles an empty table
  3. hasItem finds an item that's there
  4. hasItem returns false for a missing item
  5. orderedStats follows the order of the order list
  6. orderedStats adds nothing that isn't in order
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.