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.
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
.