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

How come it only prints one Item instead of two?

The code below is supposed to get all the Items, (separated by a comma and then space.)

But instead, I typed in Gu, Swor, (which should have printed Gun and Sword), and it printed only Gun. (luckily it was successful if I typed in one item)

local function getItems(String)
    local Table = String:split(", ")
    for i, v in pairs(Table) do
        for i, Item in pairs(game.ReplicatedStorage:WaitForChild("Items"):GetChildren()) do
            if string.sub(string.lower(Item.Name), 1, string.len(v)) == string.lower(v) then
                return Item.Name
            end
        end
    end
end

script.Parent.FocusLost:Connect(
    function()
        local Items = getItems(script.Parent.Text)
        if Items then
            print(Items)
        end
    end
)

What did I do wrong?

2 answers

✓ Accepted answer

ur returning only 1 item. so i made a table that gets sent back once it adds everything thats supposed to get returned then return the table.

local function getItems(String)
    local Table = String:split(", ")
    local ReturnItems = {}
    for i, v in pairs(Table) do
        for i, Item in pairs(game.ReplicatedStorage:WaitForChild("Items"):GetChildren()) do
            if string.sub(string.lower(Item.Name), 1, string.len(v)) == string.lower(v) then
               table.insert(ReturnItems, #ReturnItems + 1, item.Name)
            end
        end
    end
    return ReturnItems
end

script.Parent.FocusLost:Connect(
    function()
        local Items = getItems(script.Parent.Text)
        if Items then
            for i, v in pairs(items) do
                print(v)
            end
        end
    end
)

2 comments

0

nice

0

damn thanks man

The reason why it only prints the first item is because return stops the function, making it so it doesn't continue. I'm sorry if I don't make sense, but a solution you can try is adding them to a table, then return that table. Then, for the printing part, you can use a for i,v loop to print each item in the table.

local function getItems(String)
     local ItemsTable = {}
    local Table = String:split(", ")
    for i, v in pairs(Table) do
        for i, Item in pairs(game.ReplicatedStorage:WaitForChild("Items"):GetChildren()) do
            if string.sub(string.lower(Item.Name), 1, string.len(v)) == string.lower(v) then
                table.insert(ItemsTable, Item.Name)
            end
        end
    end
return ItemsTable
end

script.Parent.FocusLost:Connect(
    function()
        local Items = getItems(script.Parent.Text)
        if Items then
		for i,v in pairs(Items) do
            print(v)
        end
     end
   end
)

Hope this helps

1 comment

0

this works, so i upvoted

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