Lesson 1 of 10

Tables

Goal

An array and a dictionary in one structure

01

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.

02

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
  1. inventory holds four items
  2. The last item is the potion you added
  3. The first item is at index 1, not 0
  4. The player's hp is 100
  5. The player's name is a non-empty string
  6. table.insert was used to add the item
03

Hints

0/3
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.