So I’m doing an inventory system with stackeable and non-stackeable items, I did this function so when you try to add a greater amount than the max amount it stacks it automatically, the problem is that all the items have the same amount.
local times = math.ceil(amount/itemD.MaxAmount)
for x = 1,times,1 do
local currentAmount = amount
local i = #inventory+1
print(amount)
table.insert(inventory,i,itemD)
if amount >= itemD.MaxAmount then
print("lol "..itemD.MaxAmount)
inventory[i].Amount = itemD.MaxAmount
elseif amount < itemD.MaxAmount then
print("what")
inventory[i].Amount = amount
end
amount-=inventory[i].Amount
end
But it sets all the items to the same last value, idk why, output :
350
lol 124
226
lol 124
102
what
--------
Id : wood_log
Amount : 102
Slot : 1
-------- (x2)
Id : wood_log
Amount : 102
Slot : 2
-------- (x2)
Id : wood_log
Amount : 102
Slot : 3
Did a quick search for table duplication and this is what I found:
"Tables are passed by reference and not value, so you have to copy them manually.
An easy way of shallow copying an array is
tableCopy = {unpack(t)} -- This won't work for you're case It's only for arrays.
"
So in other words, every inventory slot is equal to data[Items][“Wood”]
So when you’re changing a value of one inventory slot it’s changing it inside the data table.
(You can do a check of this by printing data[Items][“Wood”].Amount)
Which you want to give you a 0, but it’ll give you 102.
One thing you could do and I would suggest you do is swap to a object based inventory system.
Have a folder called Inventory, Then get folders for each object, and place in number, string, and boolean values to mimic the information you need to pass. Then when you need to make a copy you can just clone it.
You are absolutely right! So I would create a function with for loops to itherate trought the data and cloning it to the new table with same key and value right?