Best way to make an inventory system

Hey guys!

I’ve made / currently making an inventory / datastore system for my game, and I’m trying to make it as robust as possible, as everything will be built off it essentially.

Currently, my inventory system uses a “relative” approach. When an item is added to the inventory, the index of it is the number of items in the inventory + 1.

This has some issues, with the main one being when an item is removed. When an item is removed, i have to decrement all the numbers above it, to make it consistent again. Aswell as this, I have armour and weapon values that refer to an item index, that also have to be decremented. I feel like this has too many moving parts.

An alternative way I’ve thought of is an “absolute” system, with the index being (amount of items ever in inventory + 1). This removes the need for consistency and the indexes would never be the same. I could remove something, then nothing would need to be decremented.

Do you think this is a better way? If not, please explain your reasoning, and other potential solutions you may have, thank you for reading!

2 Likes

Sorry, I dont understand why the indexes of the tables would be important for the inventory.
I worked many times with inventories and I never ran into issues with indexes, increase or decrease any, maybe Im the one doing something wrong, could you explain more?

The best way is the simplest way that satisfies your requirements. So… what are your requirements? If you don’t know that, you won’t be able to make a system that works for you.

Sorry for the late reply, I’m just trying to avoid the same index in an inventory

1 Like

Sorry for the late reply, the requirements are quite generic in that it can just be read and written to, and that each item in the inventory can have modifiable stats, eg. a nickname, however, this doesn’t really make a difference

But how your inventory system looks like, cause, I never needed to change indexes on a basis, maybe you would prefer using dictionaries instead of arrays, or show how your arrays looks like or why you are needing to change the indexes of whole table

I am using dictionaries, the way I refer to each item in the inventory, is via it’s index, also known as “key”

I don’t know if it is just for me, but to me, idexes and keys are different things, indexes are the positions of the elements in a table, and keys are the names of the values in a dictionary.

You talked about increments.

For simplicity, I recomend having the inventory be a dictionary with the keys being the item names and value, the amount.
You don’t have to remove a key-value pair when the amount reaches 0, you can just leave it there set as 0.

local Inventory = {
    ["Item"] = 1,
    ["Item2"] = 3
}

I still don’t understand why you need to meddle with indexes.

For inventory systems, I usually just datasave table(s) for items.