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

Pairs creates a table; how do I index the 2nd item in the table?

Asked by 8 years ago

Example:


for i, v in pairs(game.Workspace:GetChildren()) --If there are two children then the table looks like this 1 | Part 2 | Script -- I want to index the script (the script could be another part or anything, so indexing the classname won't work.

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

pairs doesn't create a table, it traverses it.


If you need to do something to all or each thing in a table, you can use a for loop with pairs.

For instance, if you want to remove all of the scripts in the workspace, you could do this:

for _, child in pairs(workspace:GetChildren()) do
    if child:IsA("Script") then
        child:Destroy()
    end
end

Note: :GetChildren() returns objects in no particular order. You should not rely on the order that GetChildren returns things in.


If you know the name of an object (and that object is unique in having that name), you don't need to use :GetChildren() at all:

workspace.MyScript:Destroy()

If you happen to have a list that you can trust the order of (again, GetChildren is not one such list), then you can use list[2] to refer to the second element of that list.

In a for loop with pairs, it does this for you:

local tab = {"apple", "banana", "cherry"}
for i, v in pairs(tab) do
    print(tab[i], i, v)
end
-- apple 1 apple
-- banana 2 banana
-- cherry 3 cherry

One final warning: pairs does not go through the list in any particular order. It's just as likely to provide banana cherry apple as it is apple banana cherry. If you need a particular order, you need to use ipairs.

Ad

Answer this question