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

Storing Variables in Tables doesn't work ( Advance ) ?

Asked by 4 years ago
Edited 4 years ago

A script inside a part that is supposed to remove a specific tool from the player's inventory.

The script works great for 1 Variable, but it stops working whenever I try to add another Tool's name to the table.

Working Example - local ToolName = "Tool"

Not Working Example - local ToolName = { "Tool", "Tool2" }

local ToolName = { "Tool", "Tool2" }

-- local ToolName = "Tool" 


function RemoveWeapons(parent)
    local weapons = parent:GetChildren()
    for i = 1,#weapons do
  if (weapons[i].className == "Tool") and (weapons[i].name == ToolName) then <-- Error
            weapons[i]:remove()
        end
    end
end

function onTouched(hit)
    local player = game.Players:FindFirstChild(hit.Parent.Name)
    local backpack = player.Backpack
    if (table.maxn(backpack:GetChildren()) > 0) then
    RemoveWeapons(backpack)
    end
    RemoveWeapons(player.Character) 
end
script.Parent.Touched:connect(onTouched)

1 answer

Log in to vote
1
Answered by 4 years ago

Try this out. Let me know if there are any problems! Please accept this answer if this helped you out! You can read about tables here.

local ToolName = { "Tool", "Tool2" }

-- local ToolName = "Tool" 


function RemoveWeapons(parent)
    local weapons = parent:GetChildren()
    for i = 1,#weapons do
        for _, v in pairs(ToolName) do -- use a for statement to loop through the items in the table
            if (weapons[i].className == "Tool") and (weapons[i].name == v) then
                  weapons[i]:Destroy() -- :Remove() is deprecated, use :Destroy() instead
              end
     end
end

function onTouched(hit)
    local player = game.Players:FindFirstChild(hit.Parent.Name)
    local backpack = player.Backpack
    if (table.maxn(backpack:GetChildren()) > 0) then
    RemoveWeapons(backpack)
    end
    RemoveWeapons(player.Character) 
end
script.Parent.Touched:Connect(onTouched) -- :connect() is also deprecated. Use :Connect() instead
0
Your script had a small error in it, fixed it, works great, thanks! Vibesgus 35 — 4y
Ad

Answer this question