Organizing a table to order of other table

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:

{
["Stone Wall"] = 42,
["Aspin Wall"] = 98,
["Oak Wall"] = 7,
["Pot"] = 15
}

The game has a dictionary which has all the building items in the game listed in a specific order:

{
["Oak Wall"],
["Spruce Wall"],
["Aspin Wall"],
["Brick Wall"],
["Stone Wall"],
["Cobblestone Wall"],
["Pot"]
}

The game compares the top table to the organized table and sorts it accordingly:

{
["Oak Wall"] = 7,
["Aspin Wall"] = 98,
["Stone Wall"] = 42,
["Pot"] = 15
}

What coding logic would I have to use to make this scenario work?

1 Like

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.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.