I have a list of building items in my game. When the player opens the building menu, I want the items listed to be in a specific order. Here’s an example of what I’m trying to do:
The game gets these items from a player’s inventory:
You can achieve this by creating a new table and inserting the items from the player’s inventory in the order specified by your game’s dictionary.
Here’s an example of how you could do this:
-- Player's inventory
local inventory = {
["Stone Wall"] = 42,
["Aspin Wall"] = 98,
["Oak Wall"] = 7,
["Pot"] = 15
}
-- Game's dictionary
local order = {
"Oak Wall",
"Spruce Wall",
"Aspin Wall",
"Brick Wall",
"Stone Wall",
"Cobblestone Wall",
"Pot"
}
-- New table for sorted inventory
local sortedInventory = {}
-- Iterate over the order table
for _, item in ipairs(order) do
-- If the item exists in the inventory, insert it into the sortedInventory
if inventory[item] then
sortedInventory[item] = inventory[item]
end
end
-- Now sortedInventory is the inventory sorted according to the game's dictionary
print(sortedInventory)
This script will create a new table sortedInventory that contains the items from the player’s inventory in the order specified by the order table. If an item in the order table doesn’t exist in the player’s inventory, it will be skipped.