[Question]Little Array Problem

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
nikneym
Citizen
Posts: 56
Joined: Sat Mar 09, 2013 1:22 pm
Contact:

[Question]Little Array Problem

Post by nikneym »

How can I get the number of elements in an array?
User avatar
Nixola
Inner party member
Posts: 1949
Joined: Tue Dec 06, 2011 7:11 pm
Location: Italy

Re: [Question]Little Array Problem

Post 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
lf = love.filesystem
ls = love.sound
la = love.audio
lp = love.physics
lt = love.thread
li = love.image
lg = love.graphics
User avatar
nikneym
Citizen
Posts: 56
Joined: Sat Mar 09, 2013 1:22 pm
Contact:

Re: [Question]Little Array Problem

Post 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. :)
User avatar
Ragzouken
Citizen
Posts: 84
Joined: Fri Aug 10, 2012 7:59 am
Contact:

Re: [Question]Little Array Problem

Post 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.
Post Reply

Who is online

Users browsing this forum: slime and 3 guests