Tables and Iteration


You can make as many variables as you like to store information in a program, but it can also be useful to put those variables together. Tables are a way to store lists of variable data, which keeps things organized and lets repeat code for each variable in the list.


Key-Value Tables

A variable is a label with some data. It has two parts, the label (what you named the variable) and the data it represents (the string, number, or Boolean that you assigned it to). In a table, that label becomes a key, because you will use it to “look up” the value.

Create a Table with Key-Value Pairs

The {} characters are used to create tables, and the = is used to assign a key to a value, and you separate the values with ,.


local producePrices = {strawberries = 3, tomatoes = 8, pumpkins = 500} -- You can also arrange these vertically to make them easier to read: local playerStats = { highScore = 15320, totalPlays = 895 }

Access a Value

You can find a value in a table using the key in "" inside of [].

You can also use . followed by the key name to get a value.


local favoriteGame = { player1 = "Roll 'Em", player2 = "Core Royale" } print(favoriteGame[player2]) -- prints "Core Royale" local player { name: "Slinkous", id: 5000 } print( -- prints "Slinkous"

Add a new Value

You can add a element to a table by assigning its key inside of "" in [] to a value with =.


local zooAnimals = { giraffe = "Eloise", lion = "Mufasa", bear = "Smokey" } zooAnimals["octopus"] = Paul

Numbered Tables

Keys and values let you store information with labels, but you can also use tables to just make a list of data. In this case, Lua automatically makes the keys for you, as numbers.

Create a Numbered Table

You can create a numbered table the same way you make one with keys and values using {}, but by only listing the values.


local groceryList = {"apples", "bananas", "oranges"} print(groceryList[3]) local luckyThings = {"four-leaf clover", 13, "rolling a 20"} print(luckyThings[1])

Unlike with a key-value table, you cannot use . to access a value

Access the Last Value

With a numbered table, you can use # to find out how many items are in the table. This can be useful if you want to find out what the last thing is, or if you want to add a new one.


local friends = {"Basilisk", "Daddio", "Montoli"} print("I have " .. #friends .. " friends!") friends[#friends + 1] = "Carbide" -- Adds a new friend at the next spot print(friends[#friends].. " is my newest friend!")

Tables Within Tables

If make a table with a variable name, this will make an numbered table, NOT a key-value pair.

You can also create tables within tables. This can be useful when you want a list where each member has more information.


local shape1 = "sphere" local shape2 = "cube" local shapeList = {shape1, shape2} print(shapeList[2]) -- you CANNOT use `shapeList["cube"]`. local scoreboard = { { name = "CoolestPlayer", score = 5001 }, { name = "TriedMyBest", score = 12 } } print(scoreboard[1].name .. " scored: " .. scoreboard[1].score) print(scoreboard[2].name .. " scored: " .. scoreboard[2].score)


One of the best uses a table is to be able to perform code on each member of it. You do this by creating a loop that repeats code a certain number of times, and repeating that code for each member of the group, iterating.


Loops are one of the most important structures in coding, given how often we need to repeat instructions until we get a result. In this course, we will focus on the for-loop.

The basic for loop creates an iterator, a number variable (usually labeled i) to start with and increases it each time it repeats until it hits the number to stop on.


for i=1, 10 do -- start is 1, end is 10 print(i .. "...") end --[[ the output: 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... ]]


Use a for-loop on a key-value table, we need to use the pairs() function so that Lua knows me mean for it to repeat the code across each value.


local cat = { color = "tabby", age = 14, name = "Agatha" } for key, value in pairs(cat) do print("The cat's " .. key .. " is: " .. value) end

The names key and value here can be anything. They are like variable names that will stand in for the key and value of each pair.


For numbered tables, you can use the ipairs() function to create pairs with the number and the value. Remember that we often use i for the number, since we are iterating

Often times you never actually use the number in your code, and programmers use _, value to show that


local raceFinish = {"tortoise", "hare"} for i, finisher in ipairs(raceFinish) do print("In place " .. i .. " is " .. finisher) end --[[ output will be: In place 1 is tortoise In place 2 is hare ]] local groceryList = {"apples", "snacks", "coffee"} for dontCareAboutThis, value in ipairs(groceryList) do print(value) end

More Examples

-- Calculating a high score local scoreboard = { playerOne = 15, playerTwo = 20, playerThree = 0 } local highestScore = 0 local highestScorer = nil for player, score in pairs(scoreboard) do if score > highestScore then highestScore = score highestScorer = player end end print(highestScorer .. " had the highest score!")
Scroll to Top