How can I count how many nils/empty slots in my table?

For example table= {}

table[1]= red

table[2]= (nil or not filled out)

table[3]= blue

#table will equal 3, but I don’t want to count any unfilled entries. Is there a way to count how many unfilled entries so I can subtract them from #table?

Or any other suggestions if there’s an easier way.

Thanks!

It may be better to use table.remove, etc., depending on what you’re doing.

#table will equal 3

It will if you’re lucky, but it’s NOT guaranteed. The length operator only works as expected for sequences. Once you’ve violated that, all bets are off.

You could do

function GetCount (t, pred) local count = 0 for \_, v in pairs(t) do -- if pred(v) then -- call your "filled out" predicate here, if you want count = count + 1 -- end end return count end

if you only have integer keys like above, or 

function GetCount (t, pred) local count = 0 for i = 1, table.maxn(t) do if t[i] ~= nil -- and pred(t[i]) -- As per the pairs() version then count = count + 1 end end return count end

otherwise.

Thanks for the help guys, after reading this, I realized table.remove would serve me better. That way everything collapses together and there are no “holes” made. 

Have you looked at: http://docs.coronalabs.com/daily/api/library/table/maxn.html

It may be better to use table.remove, etc., depending on what you’re doing.

#table will equal 3

It will if you’re lucky, but it’s NOT guaranteed. The length operator only works as expected for sequences. Once you’ve violated that, all bets are off.

You could do

function GetCount (t, pred) local count = 0 for \_, v in pairs(t) do -- if pred(v) then -- call your "filled out" predicate here, if you want count = count + 1 -- end end return count end

if you only have integer keys like above, or 

function GetCount (t, pred) local count = 0 for i = 1, table.maxn(t) do if t[i] ~= nil -- and pred(t[i]) -- As per the pairs() version then count = count + 1 end end return count end

otherwise.

Thanks for the help guys, after reading this, I realized table.remove would serve me better. That way everything collapses together and there are no “holes” made. 

Have you looked at: http://docs.coronalabs.com/daily/api/library/table/maxn.html