Page 1 of 1

[Question]Little Array Problem

Posted: Mon Apr 15, 2013 2:28 pm
by nikneym
How can I get the number of elements in an array?

Re: [Question]Little Array Problem

Posted: Mon Apr 15, 2013 2:31 pm
by Nixola
numberOfElements = #array

Note that the above only works if it's an array with consecutive integer indexes starting from 1; it won't count non-integer indexes or indexes less than or equal to 0, and it will stop at the first hole it encounters. E.g:

Code: Select all

> array = {1, 2, 3}
> array[5] = 4
> print(#array)
3
> array[4] = 5
> print(#array)
5

Re: [Question]Little Array Problem

Posted: Mon Apr 15, 2013 2:47 pm
by nikneym
Nixola wrote:numberOfElements = #array

Note that the above only works if it's an array with consecutive integer indexes starting from 1; it won't count non-integer indexes or indexes less than or equal to 0, and it will stop at the first hole it encounters. E.g:

Code: Select all

> array = {1, 2, 3}
> array[5] = 4
> print(#array)
3
> array[4] = 5
> print(#array)
5
Thanks solved. :)

Re: [Question]Little Array Problem

Posted: Mon Apr 15, 2013 4:21 pm
by Ragzouken
Just a small correction: you can't rely on # to stop at the first hole. The only guarantee is that t[#t] ~= nil and t[#t+1] == nil. On the other hand, ipairs will definitely stop at the first hole.