Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What is a Way to Create Multiple TextLabels in a Loop?

Here is my code:

plr = script.Parent.Parent.Parent.Parent
print"c.5"
inventory = plr:WaitForChild("plrinventory").ftpinv
	k =	inventory:GetChildren()
	t = {}

	print"c1"
	for i, v in pairs(k) do
		if v.iteminside.Value == true then
			print"c2"
			k = tonumber(v.Name)
			table.insert(t,v)
		end	
	end 
		if #t >= 1 then
			height = ((1/#t)/5)
			w = 1
			s = {}
			for i, v in pairs(t) do
				z = Instance.new("TextLabel")
				z.Size = UDim2.new(1,0,height,0)
				z.Parent = script.Parent
				z.Position = UDim2.new(0,0,height*2,0)
				z.Text = v.Sword.Name
				z.TextScaled = true
				table.insert(s,v)
			end
		end

My problem is that I want to create multiple TextLabels, but I can't seem to make more than one because there is only one variable. Is there anyway to get passed this?

1 answer

✓ Accepted answer

Okay, let's first fix a bunch of things.

Tab your code correctly. You can also simplify a few things, like ((1/#t)/5) is really just 1 / 5 / #t or 0.2 / #t.

Don't use print"c1", that's just bad style. Use the parenthesis.


Use good variable names: k doesn't tell me anything. Let's say items. Then v in the first loop is an item.

Thus t are the items that are actually there, I guess. I'll just call it have.

You assign to k on line 11, but don't use that value. So that assignment is meaningless.

Again, let's call v item. Now you add things to s but don't use s. Also, s is just a copy of have.

You can also use the second parameter of Instance.new as the parent, which will cut one line.

Use local variables. z is defined in a loop, so you definitely want it to be local.


This will, in fact, make one new TextLabel per element in the table have. It doesn't matter how many variables represent it, it matters how many times the code is executed -- and Instance.new will be done for each iteration of the loop.

However, you gave every element the same Position so they will all be on top of each other.

Their position should be UDim2.new(0, 0, height * (index - 1), 0) where index is a number 1, 2, 3, ... assigned to each element, e.g., i in that loop. -- It needs to vary depending on which item you're looking at.

plr = script.Parent.Parent.Parent.Parent
print("c.5")
inventory = plr:WaitForChild("plrinventory").ftpinv

items = inventory:GetChildren()

have = {}

print("c1")
for _, item in pairs(items) do
	if item.iteminside.Value then
		print("c2")
		table.insert(have, item)
	end 
end 

if #have >= 1 then
	height = 0.2 / #have
	for i, item in pairs(have) do
		local z = Instance.new("TextLabel", script.Parent)
		z.Size = UDim2.new(1, 0, height, 0)
		z.Position = UDim2.new(0, 0, height * ( i - 1), 0)
		z.Text = item.Sword.Name
		z.TextScaled = true
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.