Klink45
Klink45

Reputation: 449

Check if something has children in ROBLOX Lua?

I need to check if something has children in ROBLOX Lua. I know of FindFirstChild(string) which finds the first child with a name matching string, and I have been using that to see if the instance has a certain child in it, but now I want to see if it has ANY at all. I was hoping for something like:

if Instance:GetChildren() then
  --Do something
end

How do I do something like that?

Upvotes: 1

Views: 5119

Answers (4)

Open Pees
Open Pees

Reputation: 13

here's one way you could find that out:

x = 0

for i, v in pairs(script:GetChildren()) do
    x += 1
end

if x > 0 then
    print("it has children")
end

it's not the most efficent but it's pretty simple and works

Upvotes: 0

Yegor Guy
Yegor Guy

Reputation: 1

if Object.GetChildren() then
   --code here
end

Upvotes: 0

Zipper
Zipper

Reputation: 180

I suggest using the hashtag operator or table.getn

-- Hashtag
if(table.getn(Instance:GetChildren()) > 0) then
    -- ...
end

if(#Instance:GetChildren() > 0) then
    -- ...
end

Upvotes: 0

Klink45
Klink45

Reputation: 449

This method will get a table of the Instance's children and check if it is more than 0, meaning it has children.

if #Instance:GetChildren() >0 then 
  --It has children!
end

Upvotes: 3

Related Questions