Adding item to inventory (if item does not already exist)
for i, v in pairs(User.Inventory) do
if v.Type == nil then
User.Inventory[i] = {Type = 'Material', Name = item, Quantity = 1}
InventoryManager:Update(player)
return true
end
end
No errors, problem lies in the fact that it’s putting the item in slot 7 and not slot 3. I want it to basically find the first empty slot and put it there
Your issue may be that {} == nil resolves to false, i.e. an empty table is not classified as a nil object. Not sure why it’s putting it in slot 7 though…
Try replacing if v.Type == nil then with if v == {} then and see if that works
With this pairs should work fine. ipairs uses an iterator instead of an index which is why the value you’re still setting the wrong index in your table. It’s basically because your table isn’t sorted the way you think it is.
Using keys 1-9 is pointless. Those values are automatically assigned in an array structured table anyway. The only difference is that your 1-9 isn’t the same as the array’s 1-9 once its sorted automatically. You don’t want to go about looking up keys in a table with numbers because Lua is going to think they’re array indices.
Letting the values be assigned by the order they’re entered into the table should be fine, even for your UI.
Can’t say the same thing for saving and loading that data though. You probably want to come up with a better key name… even something as simple as making the numbers a string would be easier to reference as a table key lookup, just keep in mind that you’ll need to tostring the index “number” you’re trying to look up.
Regarding the earlier replies, a table is only ever equal to itself, i.e.
t={}
t == t
or
a = {}
b = a
a == b
is true, but
{} == {}
or
{foo=1}=={foo=1}
Are both false.
Instead of using in pairs, which does not have a guaranteed order and will not always go 1,2,3,4 etc., use for i=1, #User.Inventory do
instead, or use ipairs which will also work in order for an array without missing keys.