Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Using one for loop instead of multiple?

Asked by
N33H 19
4 years ago

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

Log in to vote
0
Answered by
Sindrotex -41
4 years ago
Edited 4 years ago

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

Ad

Answer this question