Counting children

The golden rule about micro-optimization is to not do it.

1 Like

You appear to be the one confused here.

While #string will print the number of bytes, using #table will print the number of items inside of it as seen here:
image
I’m not entirely sure where the confusion came in, but @greenboo5 is not referring to the same concept.

It’s easy to see why you would think that #string and #table would return the same type of information, but they represent different ideas if that makes sense. If you don’t trust #table to return accurate data though, you can write an __len metamethod to count up the tables contents for you.

local tbl = {1,2,3}
setmetatable(tbl,{__len = function() local val = 0 for i,v in pairs(tbl) do val += 1 end return val end})

print(#tbl)

This isn’t micro-optimization; it’s called bad practice. For future cases, you should know when to use a arithmetical operator and when to perform function calls, as function calls are more expensive than simple operations.

1 Like

You’re calling the GetChildren() method just to loop through and count the children… when the “#” operator is specifically made for retrieving the length of an array.

no :heart:

3 Likes

This thread is just a meme at this point.

based aaaaaaaaaaa a aaa

1 Like

You should use # behind a table or simply use table.getn() (Both does same thing)

And then use a child added and child removed event.

Like this:

-- folder:GetChildren() returns a table and doing # behind a table will return the ammount of indexes there.
local currentAmmount = #folder:GetChildren()
-- If there were 3 items it would be 3.

local function newAmmount()
      currentAmmount = #folder:GetChildren()
end
folder.ChildAdded:Connect(newAmmount)
folder.ChildRemoved:Connect(newAmmount)
-- Basically whenever a child is added or removed then it will update the current value to the ammount of children in there.

why not just count += 1 and count -= 1 when a child is added and removed? Much better practice than performing a O(n) function call every time a child is added / removed.

1 Like

You could do that, that was just an example script

Yes, he is calling a linear time complexity function. Which in this case arithmetic would be better, but again it barely has a difference.

It indeed has no differences, im pretty sure about it.

Both has the same results.

The point isn’t about how significant or optimized it is; it’s about bad practice for future references (in which you could be needing optimization, dunno).

I agree, its faster and easier to understand? There is no reason to have an argument over this…

1 Like

I know right (30 charactersssss)

1 Like

Easy!

local myTable = game.Workspace.something.that.you.want.here
local numberOfChildren = #object:GetChildren()
5 Likes