Sorting an array based off of key

I’m making a backpack system, and I have buttons bound to specific items in a player’s inventory. The challenge of making this custom system is resorting the table and changing the interface as soon as an item is removed or an item is added. I made a rough illustration of the code of how I want it to happen on paper, where 1’s item is removed, and the 2 item needs to go up to the 1 index.

2 Likes
local Items = {
  [1] = "Item";
  [2] = "Item";
  [3] = "Empty";
  [4] = "Item";
  [5] = "Empty";
}

local function SortHotbar()
  table.sort(Items, function(a, b)
    return a == "Item" and b == "Empty"
  end)
end

Items[2] = "Empty"; SortHotbar()
print(Items)
--[[ -> {
  [1] = "Item";
  [2] = "Item";
  [3] = "Empty";
  [4] = "Empty";
  [5] = "Empty";
}]]

2 Likes

I believe table.remove() does this for you.

Also, you know you don’t have to manually write each index for an array, right? You can just do this:

local array = {
    "Foo",
    "Bar",
    "Baz"
}
1 Like

Instead of putting “Empty”, just use table.remove(ItemsInventory, index) and call the function which updates the UI, you don’t need to specify numeric indices when making tables btw, it’s a preference though.

2 Likes

Correct, but it’s just easier to comprehend for me as you said.

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