Need help with "in pairs()" loop

This is an example script: Screenshot_2194

I have model1 and model2 and i want to print the names of the parts that are in them, but is there a way to print the names of the parts inside both models without using another loop? The question is kinda dumb but i can’t seem to find any other way to do this

1 Like

You can just print model1 and model2, it would print out a table I guess.

If there is something different in the model except parts and if some of the parts are inside them, you should use

GetDescendants()

This will get everything inside the model and its children.

And also, if you want some defined parts like Parts, you can use

if v:IsA("Part") then
    --something
end

You can add the table model2 to model1.

local model1 = game.Workspace.Model1:GetChildren()
local model2 = game.Workspace.Model1:GetChildren()

for i, v in ipairs(model2) do
      table.insert(model1, v)
end

for i, v in ipairs(model1) do
      print(v.name)
end

You could use a nested loop :man_shrugging:

for _, model in pairs({model1, model2}) do
    for _, descendant in pairs(model:GetDescendants()) do
        print(descendant)
    end
end
3 Likes

Yes, pretty simple

local ChildTable = {
modell,
model2
}
for i, v in pairs(ChildTable) do
print(v.Name)
end

**Do not actually use this solution
Yes technically there are ways to iterate over two tables like these using only a single loop, however code readability, and likely performance suffers when you take this approach. It may just be the case that using two loops (or creating an additional table by merging the two tables into one table and then iterating over the new table) is more effective.

Here’s one way to iterate over both tables using a single loop (although it doesn’t use the pairs iterator)

local model1 = workspace.Model1:GetChildren()
local model2 = workspace.Model2:GetChildren()

for i = 1, #model1 + #model2 do
    print(({model1, tab2})[math.clamp(math.ceil(i/#model1), 1, 2)][i - (#model1 * math.clamp(math.floor((i-1)/#model1), 0, 1))])
end

Once again, do not use this solution. I just found it fun to try and figure out how to do this using only a single loop but it is by no means the most effective performance-wise or in terms of code readability (in which case it is actually a nightmare). Your best case scenario is to either combine the tables beforehand or just use two separate loops.

2 Likes

This is incorrect. It will only print nil twice because the for loop is iterating over a table of tables, both of which have a nil entry on key “Name”.

1 Like

You should use :GetDescendants() or :GetChildren() when using for loops like for I, v in pairs(model:GetDescendants()) do like that