Lesson 3 of 10
The table library
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
Insert, remove, join and sort
Explanation
The table library has everything you need to manage a list. table.insert(t, pos, v) puts the value at position pos and shifts everything after it up one position, and table.remove(t, pos) removes the element at that position, returns it, and closes the gap with what comes after. Leave out pos and both of them work on the end of the list.
table.concat(t, ", ") joins the elements into a single string, and it only accepts strings and numbers, so collect the names in a list before you join them. table.sort(t, less) sorts the list in place without creating a new one, and the comparison function less(a, b) answers a single question: does a come before b? table.sort doesn't keep equal elements in their original order, so if you want their order fixed, compare them by a second criterion.
The classic mistake here is writing >= in the comparison function. It has to return false for two equal elements in either order, but >= returns true, so table.sort either throws invalid order function for sorting or scrambles the order without telling you. So stick to > or < in a comparison function.
Your task
For the combat turn system, fix sortBySpeed(list) so the fastest unit goes first and units with the same speed are sorted by name in ascending order. Then write rush(list, unit), which puts the unit at the front of the turn order, nextTurn(list), which removes the first unit and returns it, and turnOrder(list), which returns the names joined with ", ".
Checks
5 checks- sortBySpeed puts the fastest first
- Units with equal speed are sorted by name in ascending order
- rush puts the unit at the front of the turn order
- nextTurn removes the first unit and returns it
- turnOrder joins the names with a comma