pairs and iPairs
Students will be able to:
pairs and iPairs
ipairs() are functions that can be used with a for loop to go through each element of an array or dictionary without needing to set starting or ending points.
pairs() is used with dictionaries, and
ipairs() is used with arrays. The “i” in
ipairs() stands for “index.”
Dictionaries and pairs
pairs() can be used to work with a dictionary element’s key, value, or both. In the
for loop below, the first variable is the key. The second variable is the value. The dictionary that you want to work with is passed in to
Arrays and ipairs
Remember, the “
ipairs() is for “index.” Use
ipairs() and arrays in combination with a
for loop to work with ordered values like leaderboards.
Practice - Restaurant Soup Simulator
Let’s make some soup for a restaurant simulator where players pick from a list of possible soup ingredients. The ingredients will be stored as keys, and the values will start off as
false so the players only get what they select. Use
pairs() to see what was picked, and then
ipairs() to print the list of ingredients.
- Create a new dictionary named
menu. Add 3 - 5 key-value pairs where the key is the ingredient and the value is false.
- Beneath the
menudictionary, add an empty array which will be filled with the customer’s choices later.
pairs()to check if each ingredient in the dictionary is marked
true, add the ingredient to soup.
- Repeat the order back to the customer. On your own, try to:
- Check if there is a menu item in
isInSoup. If so, print "You ordered soup with: ".
ipairs()to go through the
isInSouparray and print each ingredient.
- Test by changing at least one menu item to
- Add an
elsestatement which tells customers if no ingredients were selected.
Challenge - Waiter NPC »
Challenge - Allow Players to Place Orders »
Advanced Challenge - Make Me Some Soup Simulator »
Create a restaurant simulator where players are the chefs! Players will have to put together ingredients to match the order given to them by the waiter.
- Create in-game props for 3 - 5 different ingredients.
- Create 3 - 5 recipes using dictionaries similar to the one in this lesson.
- Create an array that holds all of the recipes.
- Randomly select a recipe and use an NPC to tell players what the ingredients are.
- Create a new dictionary to make a recipe based off which prop ingredients the player touches.
- Compare the player’s recipe to the recipe chosen by the NPC.
- Increase the challenge by adding an extra condition, such as a timer.
Previous Intro to Dictionaries Next Intro to Module Scripts