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

Getting the total of children? [closed]

Asked by 9 years ago

Using GetChildren() how do i get the total amount of children are their in the workspace?

Locked by NinjoOnline, woodengop, and Redbullusa

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

1 answer

Log in to vote
2
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
9 years ago

You can get the total number of direct children(e.g. doesn't count parts inside of parts) by using the # Operator. The # Operator gets the length of any given string or table. And since the GetChildren function returns a table, it will get the length, or how many children there are(:

Example;

local model = workspace.Model
local amount = #model:GetChildren()
print(amount) --> Will print the number of direct children

Note: This only gets the amount of direct children in your model. If you want to get every child inside the model you're going to have to use a method in lua called recursion. Recursion is essentially re-iterating a function upon itself. Like if you were to go;

function a()
    a()
end

This is recursion. But be wary when using recursion, as you can easily end up with a stack overflow. Stack overflow errors happen when you call a function inside itself too many times in a short amount of time with no yeild. The code above would give you a stack overflow error.

So, to use recursion to your advantage? You need to make a function that iterates through a model with the Pairs method in a generic for loop, adding 1 to a variable outside of the function each time it iterates. Then, you can recall the function on itself with each child;

local num = 0 --variable

function recurse(model) --function 'recurse'
    for i,v in pairs(model:GetChildren()) do --iterate through model
        num = num + 1 --add 1 to 'num' variable
        recurse(v) --recurse the 'recurse' function(:
    end
end

print(num)

Now, say you can't have that variable outside of the function because of the circumstances in your code.. we can fix this by having a local function inside of the main function. We can define the variable inside of the main function and use the local function for the recursive mechanics;

function GetNumChildren(model) --main function
    local num = 0 --variable
    local recurse = function(mod) --recursive function
        for i,v in pairs(mod:GetChildren()) do
            num = num + 1
            recurse(v)
        end
    end
    recurse(model) --call the recursive function
    return num --return the variable
end

print(GetNumChildren(workspace.Model))

Most of the time you won't see yourself needing to do the latter, but it's always useful to know different methods of doing things(:

Hope I helped!

Ad