lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, 2010-12-14 at 13:04 +0100, Gunnar Zötl wrote:
> > I think that a big part of the problem is that people feel 'nil'
> > should somehow be treated differently from other values when storing
> > it in a table  used as an array. I don't see why.
> 
> oh, this is easy. Nil is nothing, no value, not even null, just plainly a name for the absence of a value. So if you assign nil to a variable or a table key, you are saying that there is no value stored there. And as nothing is very different from anything else, it should be treated differently. As an example, storing nil as a value for a key in a table, thus removing any value stored there and replacing it with nothing, will also remove the key, which seems perfectly reasonable to me.

That is exactly how I understand and USE nil. I am interested to see an
application/algorithm where an array with "nil" values is required, and
it is inconvenient/impossible to solve it using sentinel values (like
NoValue = {}) or more advanced data types built on top of table
semantics.

With Lua 5.2 and __len and __ipairs working for tables, you can really
do anything without needing to change the current Lua core semantics.
With appropriate shortcuts, it does not even clutter the source very
much, i.e.:

local T = ArrayWithHolesConstructor -- a custom datatype constructor

local a = T{} -- empty, fill it with a:append(), a:remove() etc...
local b = T{1, nil, 3, nil, 5} -- standard Lua semantics for nil
local c = T(1, nil, 3, nil, 5) -- uses select('#',...) to get the size