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

How do I manipulate 2 or more tables in a for loop (on a faster way)?

Asked by 5 years ago
Edited 5 years ago

I will put the code here, then walk you through my problem. (Bear with me please...)

-- Variables for inference
local structure = game.Workspace.Intro.Building_2:GetDescendants() 
local extras = game.Workspace.Intro.Extras:GetDescendants()
-- I defined 2 tables for each models.
local trigger = script.Parent
local sound = game.Workspace.Intro.Building_2.Sound
trigger.Touched:connect(function()
    for i,v in pairs (structure) or (extras) do -- I tried putting 2 tables
        if v:IsA("Part") then
            wait()
            v.Anchored = false
            v.BrickColor = BrickColor.new("White")
            v.Material = "Neon"
            sound:Play()
        end
    end

    script.Parent:Destroy()
end)

When I tested it. It yields this error when I touched the trigger: Workspace.Intro.Trigger.Script:7: bad argument #1 to '(for generator)' (table expected, got nil)

But it works when I do this:

trigger.Touched:connect(function()
    for i,v in pairs (structure) do
        if v:IsA("Part") then
            wait()
            v.Anchored = false
            v.BrickColor = BrickColor.new("White")
            v.Material = "Neon"
            sound:Play()
        end
    end

    script.Parent:Destroy()
end)

-- I separated the 2 tables for every loop.

trigger.Touched:connect(function()
    for i,v in pairs (extras) do
        if v:IsA("Part") then
            wait()
            v.Anchored = false
            v.BrickColor = BrickColor.new("White")
            v.Material = "Neon"
            sound:Play()
        end
    end

    script.Parent:Destroy()
end)

It seemed to yield no error at all. And it worked. But is there some way to efficiently type this? I'm a beginner scripter so I hope you guys can explain it in an easier way?

0
Because iterating though 2 tables at a time would return nil, that's why you use nested loops . Next_Byte 21 — 5y

Answer this question