How to clone a text label for every item in table?

I’m practicing with Datastore2 and after a tutorial. The script creates a textlabel for every item in the player’s inventory with the item name and amount next to it. I want to instead clone the textlabel for every amount of the item.
Here’s my script:

local Player = game.Players.LocalPlayer

–Services
local ReplicatedStorage = game:GetService(“ReplicatedStorage”)
local HttpService = game:GetService(“HttpService”)

–Locals
local InventoryGui = script.Parent
local Container = InventoryGui:WaitForChild(“Container”)
local Template = InventoryGui:WaitForChild(“Template”)

local DataFolder = ReplicatedStorage.ReplicatedData:WaitForChild(Player.UserId)

–Bind to StringValue.Changed
DataFolder.Inventory.Changed:Connect(function(encodedData)
–Decode JSONArray
local dataTable = HttpService:JSONDecode(encodedData)

--Iterate through all entires
for itemName, amount in pairs(dataTable) do
	--Find label in container
	local label = Container:FindFirstChild(itemName)
	
	--If label doesn't exist, clone

	if (not label) then
		label = Template:Clone()
		label.Name = itemName
		label.Parent = Container
		label.Visible = true
		
	end
	
	--Update text
	label.Text = itemName .. ": x" .. amount
end

end)

I think you mean something like:

for i, v in pairs(dataTable) do
    for j, q in pairs(v) do
        --Find label in container
	    local label = Container:FindFirstChild(itemName)
	
	    --If label doesn't exist, clone
	    if (not label) then
		    label = Template:Clone()
		    label.Name = j
		    label.Parent = Container
		    label.Visible = true
	    end

	    --Update text
	    label.Text = j .. ": x" .. q
    end
end

If it is not displayed correctly try to invert j with q and vice versa (not those on the for line)

If that doesn’t solve your problem, could I have an example of your table / array / dictionary?

No, no sorry what I mean is that it creates a label for every item, and the text for the label says “item:quantity” basically. Instead, I just want to make a label for every amount of the item I have.
So rather than the label saying:
“lemons:x3”
It would be:
“lemons”
“lemons”
“lemons”

something like this?

local items = {}

--Iterate through all entires
for itemName, amount in pairs(dataTable) do
	--Find label in container
	local label = Container:FindFirstChild(itemName)
	
	--If label doesn't exist, clone
	if (not label) then
        items[itemName] = 0

		label = Template:Clone()
		label.Name = itemName
		label.Parent = Container
		label.Visible = true
	end
	
	--Update text
    items[itemName] = items[itemName] + 1
	label.Text = itemName .. ": x" .. items[itemName]
end

Okay let me try that out. I’ll update in a second thank you

1 Like