Difference between # and NumChildren

Hi guys,

Help me out here.

When I write for loop inside a function I have to do

for i = 1, #elements do
– code here

But when I do
for i = 1, elements.numChildren do
– I get an error “for loop element must be a number”.
When I print elements.numChildren value I get “nil”.

I do not get why, because elements group is declared at top of main.lua with word “local”, so it should be accessed within all functions (it is not local to any function)?

Many thanks.
Ivan

‘numChildren’ should be used for display groups or containers, while # is used for tables.

local elements = {} -- This is a table local group = display.newGroup() -- This is a display group for i = 1, 10 do elements[i] = display.newCircle( group, 0, 0, 10 ) end print( "Circles in table 'elements' == " .. tostring( #elements ) ) print( "Circles in display group 'group' == " .. tostring( group.numChildren ) )

Hi Roaminggamer, As always, you are prompt, clear, simply the best :slight_smile: Guys, Roaminggamer rocks! :slight_smile: Thank you. Ivan

For tables, there is also table.maxn() (https://docs.coronalabs.com/api/library/table/maxn.html) which returns the count of items in the table. For indexed tables where there are no “nil” holes, # and maxn() should return the same value. .maxin() is good for non-indexed tables. It is resource expensive though.

Rob

Thank you Rob.

Ivan

‘numChildren’ should be used for display groups or containers, while # is used for tables.

local elements = {} -- This is a table local group = display.newGroup() -- This is a display group for i = 1, 10 do elements[i] = display.newCircle( group, 0, 0, 10 ) end print( "Circles in table 'elements' == " .. tostring( #elements ) ) print( "Circles in display group 'group' == " .. tostring( group.numChildren ) )

Hi Roaminggamer, As always, you are prompt, clear, simply the best :slight_smile: Guys, Roaminggamer rocks! :slight_smile: Thank you. Ivan

For tables, there is also table.maxn() (https://docs.coronalabs.com/api/library/table/maxn.html) which returns the count of items in the table. For indexed tables where there are no “nil” holes, # and maxn() should return the same value. .maxin() is good for non-indexed tables. It is resource expensive though.

Rob

Thank you Rob.

Ivan