Kristofer Karlsson wrote:
> I think the source of problems with nil isn't its
> existence, but its double meaning.
> The two senses of nil - nothing is stored here,
> and a value that is unlike other values - …
joao lobato wrote :
> 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
Maybe you should/could consider nil only as « a value that is unlike other values », not as « nothing is stored here ».
It has a type (type(nil) == "nil"), it can be assigned to a variable (local var = nil), it can be passed as a parameter (print(nil)) and it can be returned from a subroutine (function() return nil end).
(So, according to the Wikipedia definition, it is a first-class value: http://en.wikipedia.org/wiki/First-class_object)
It is unlike other values NOT because of its type, but because of its uses.
- It has only one value (boolean has only two values)
- It is the value given when we don’t know what else to give (not defined, unknown value, an error occured, …)
- Tables don’t store nil values, and accessing an undefined table member give nil (so, as storage in lua is done with tables most of time, nil is considered as 0-sized for storage)
You could compare nil to the character ‘\0’ in a string, which is a common typed value (char) but has a special meaning (end of string).
As strlen(some_string) give the index of the first ‘\0’ character in C, #some_table give the last non-nil value in Lua (within some conditions J).
But I agree that it’s easier to think (and to teach) that nil means « nothing is stored here », but it’s the same (no double meaning). ;)
Best regards, Julien Duminil
I think the source of problems with nil isn't its existence, but its double meaning. The two senses of nil - nothing is stored here, and a value that is unlike other values - are separate in most other languages. For example, in Python, "nothing is stored here" is signified by raising an exception, and "value that is unlike other values" is signified by None. The problems with nil rise from the fact that it has to handle both cases.