Lesson 5 of 10

Holes in lists

Goal

Remove with table.remove, not nil

01

Explanation

#t doesn't count elements. It looks for a border: a position that holds a value and is followed by a position holding nil. A contiguous list has only one border, its number of elements, but once there's a nil in the middle, a hole, the list has more than one border and # is allowed to return any of them.

So don't remove an element from a list with inventory[2] = nil. #inventory may stay the same, and ipairs stops at the hole, so everything after it disappears from every loop without a single error message. Remove it with table.remove(inventory, 2) instead, which shifts everything after it down one position so the list stays contiguous. If the holes are intentional, like the empty slots on a hotbar, don't rely on # to tell you the size: store it yourself in a field such as size.

Be careful when you remove items inside a loop that starts at the beginning of the list. Each removal moves the next element into the position you just checked, so it slips past the check. And because the loop's end was worked out once, when the loop started, the loop reaches positions that are now empty and you get an error. That's why you start from the end of the list: for i = #items, 1, -1.

02

Your task

Fix removeBroken(items) so it uses table.remove to delete every item whose durability is 0 from the list itself. Then write emptySlots(bar), which counts the empty slots from 1 to bar.size.

Checks

5 checks
  1. removeBroken removes the broken items
  2. removeBroken leaves no hole in the list
  3. Two broken items in a row are both removed
  4. emptySlots counts the empty slots
  5. emptySlots works even when the first slot is empty
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.