Lesson 1 of 10
Tables
- 11 min
- 6 checks
- 3 hints
- Go to task
Goal
An array and a dictionary in one structure
Explanation
Lua has just one data structure, the table {}. You use it as an array, like {"sword", "shield"}, as a dictionary, like { hp = 100 }, and as an object and a class too: in Lua, all of these are tables.
One thing trips up people who come from other languages: indexes start at 1, not 0. The first element is inventory[1], and #inventory gives you the number of elements, so the last one is inventory[#inventory].
To add an element, use table.insert(t, v), which puts it at the end of the table. It reads more clearly than t[#t + 1] = v, even though the two do the same thing.
Your task
Create a table inventory with three elements, then add "potion" to it with table.insert. Then create a table player with a name and an hp of 100.
Checks
6 checks- inventory holds four items
- The last item is the potion you added
- The first item is at index 1, not 0
- The player's hp is 100
- The player's name is a non-empty string
- table.insert was used to add the item