lua-users home
lua-l archive

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


On 02/15/2011 07:42 AM, joao lobato wrote:
t.key == nil is the test and t.key = nil is the delete operation. nil
is not a first-class value nor is it meant to be: you can't store nils
in tables and that's a feature, not a bug.


I agree - right now, nil is not a first-class value. It's more like a first-and-a-half-class value. Because, as Julien Duminil mentioned above, nil has just enough first-class value properties (having a type, assignability, parameter passing, existing on the stack, and returning) that it gets confused with one.

And there are lots of other languages - Ruby, Python, JavaScript, C#, SQL, etc. - where nil/None/null *is* a bona fide first-class value. And the fact that Lua's nil is not first-class makes dealing with outside data a lot harder than it should be. (i.e. having to use a function to represent null in a JSON decoder - not only does it make no sense, but it also doesn't test as false like a proper nil would)

Anyway, a more detailed version of my idea would be:

- Tables keep track of which fields are assigned to, and can actually store nil. - An index operation on a table where the key does not exist returns no value. - Two additional operations on tables are provided - a "contains" operation (i.e. t has key) that tells whether the table has the key set as a value, and a "delete" operation (i.e. delete t[key]) that removes the field completely. - If you attempt to compare, do math with, concatenate, use in a boolean, bind to a local, pass as an argument to a function (besides the last one) or store in a table a value that isn't actually there (i.e. t[key] for a non-existent key, or ... when no varargs were passed), nil is substituted for it. - The array length operator is modified to count up to the highest field that is *defined*, not the highest field that is not nil. (This allows tables to contain nils.) - Iterators cancel not when the iterator function returns nil, but when it returns no values whatsoever. (This allows iterators to return nils.)

So yes, I am part of the "Make nil a first class value" crowd. (I also think varargs should be a first-class value, but that's another thread.) Having nil as a first-class value is more consistent and interoperable than having it as a first-and-a-half-class value.
--
Regards, Matthew Frazier