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

Using one for loop instead of multiple?

I'm currently working on a custom inventory UI for my game, this section of code goes through their backpack and scans through tools, it works just fine, however I'm wondering if there is a better way to approach this than just throwing a bunch of for loops in.

local function SetSlots()
	for Backpack, ItemOne in pairs(Backpack:GetChildren()) do
		if ( ItemOne:IsA("Tool") and ItemOne.Values.Slot[v] == 1) then
			SlotContents.One = ItemOne
		end		
	end
	
	for Backpack, ItemTwo in pairs(Backpack:GetChildren()) do
		if ( ItemTwo:IsA("Tool") and ItemTwo.Values.Slot[v] == 2) then
			SlotContents.Two = ItemTwo
		end		
	end
	
	for Backpack, ItemThree in pairs(Backpack:GetChildren()) do
		if ( ItemThree:IsA("Tool") and ItemThree.Values.Slot[v] == 3) then
			SlotContents.Three = ItemThree
		end		
	end
end

1 answer

Instead of for backpack, itemNumber, have all the items in a table and loop through that

I see you're using pairs, which I'm pretty sure doesn't allow you to have them ordered as 1, 2 and 3 by their name, meaning 2 could be at index 1, but if that's not a problem, then it's as simple as making a table of the items, so like this:

local itemTable = {}
for i, v in ipairs(itemTable) do
itemTable[i]:IsA("Tool")...
end

or use V instead but ight

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