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.
Tables
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 ,.
Examples:
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
}Code language:Lua(lua)
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.
Examples:
local favoriteGame = {
player1 = "Roll 'Em",
player2 = "Core Royale"
}
print(favoriteGame["player2"]) -- prints "Core Royale"local player = {
name = "Slinkous",
id = 5000
}
print(player.name) -- prints "Slinkous"Code language:Lua(lua)
Add a new Value
You can add a element to a table by assigning its key inside of "" in [] to a value with =.
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.
Examples:
local groceryList = {"apples", "bananas", "oranges"}
print(groceryList[3])
local luckyThings = {"four-leaf clover", 13, "rolling a 20"}
print(luckyThings[1])Code language:Lua(lua)
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.
Examples:
local friends = {"Basilisk", "Daddio", "Montoli"}
print("I have " .. #friends .. " friends!")
friends[#friends + 1] = "Carbide"-- Adds a new friend at the next spotprint(friends[#friends].. " is my newest friend!")Code language:Lua(lua)
Tables Within Tables
If you 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.
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
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.
Example:
for i=1, 10do-- start is 1, end is 10print(i .. "...")
end--[[ the output:
1...
2...
3...
4...
5...
6...
7...
8...
9...
10...
]]Code language:Lua(lua)
Pairs
To 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.
Example:
local cat = {
color = "tabby",
age = 14,
name = "Agatha"
}
for key, value inpairs(cat) doprint("The cat's " .. key .. " is: " .. value)
endCode language:Lua(lua)
The names key and value here can be anything. They are variable names that will stand in for the key and value of each pair.
IPairs
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
Examples:
local raceFinish = {"tortoise", "hare"}
for i, finisher inipairs(raceFinish) doprint("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 inipairs(groceryList) doprint(value)
endCode language:Lua(lua)
More Examples
-- Calculating a high scorelocal scoreboard = {
playerOne = 15,
playerTwo = 20,
playerThree = 0
}
local highestScore = 0local highestScorer = nilfor player, score inpairs(scoreboard) doif score > highestScore then
highestScore = score
highestScorer = player
endendprint(highestScorer .. " had the highest score!")Code language:Lua(lua)
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
3rd Party Cookies
This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.
Keeping this cookie enabled helps us to improve our website.
Please enable Strictly Necessary Cookies first so that we can save your preferences!