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

How do I make a table of children of an instance and have a loop go through them?

Asked by 3 years ago

I'm making a reload system and have a mechanic where the player can drop the mag in order to reload the gun faster. Prior to scripting this mechanic, I had it so that everytime the player hit reload, a function would add +1 to a string and then would find that string in the "Magazines" folder. This won't work anymore as let's say the player drops Magazine2. If the player tries to reload from Magazine1, there won't be a Magazine2 to reload. I've never dealt with tables before and have no idea where to start with this. I looked at the API and don't really get it.

1 answer

Log in to vote
1
Answered by
R_alatch 394 Moderation Voter
3 years ago
Edited 3 years ago

You can simply do object:GetChildren() to return an array of the children inside that object. From there, you can do #array to get the length of the array.

You can loop through the array using for i = 1, #array where i is the current index the for loop is on. 1 is the number the for loop begins at and #array is what i will go up to.

local object = workspace.Model
local array = object:GetChildren()

for i = 1, #array do
    print(i)
end

--Output:
1
2
3
...

To get the object associated with the index you're on, use object[i] inside the for loop.

Another method is a pairs for loop where i is the index and v is the value. Pairs takes an array and will give you the index and it's corresponding value for every item in the array. This is the most common way of looping through arrays and using their value (or index) to achieve what you need with it. It is also recommended you use ipairs for arrays and pairs for dictionaries if you plan to use this method. Either way works for arrays though, so if you forget to use ipairs it will still function correctly.

local object = workspace.Model
local array = object:GetChildren()

for i, v in ipairs(array)
    print(i .. " " .. v.Name)
end

--Output:
1 Object name
2 Object name
3 Object name
...

Hope this answers your question!

0
Thanks! I'll try this method LeedleLeeRocket 1257 — 3y
Ad

Answer this question