How can one put a nil value in an array?

Putting nil directly into an array causes a 'hole' that will confuse the length operator. There are two ways to get around this. One approach is a sparse array with an explicit size; the iterator must return the index and the value:

local sa = {n=0}
function append(t,val)
 t.n = t.n + 1
 t[t.n] = val end function sparse_iter(t)
 local i,n = 1,t.n -- where t.n must be managed specially! #t will not work here.
 return function()
 local val = t[i]
 i = i + 1
 if i > n then return nil end
 return i,val
 end end append(sa,10)
append(sa,nil)
append(sa,20)
for i,v in sparse_iter(sa) do ... end

The other approach is to store a special unique value Sentinel in place of an actual nil; Sentinel = {} will do. These issues are discussed further on the wiki.



Back