> "you may end up replacing nil with explicit type-specific sentinel values or option types that have similar semantics."
You are completely and absolutely right! The problem with nil is that there are two scenarios in which comparing a variable with nil can be true.
- The first one is that we, ON PURPOSE, have set that variable to nil as a sentinel value. This is correct. No problem with it.
- The second one is that we, BY MISTAKE, have forgot to initialize the variable and just declared it. This is part of the "billion dolar mistake", as Tony Hoare named it.
> "the immediate reaction from my head is how you would approach this?
> local foo
> local bar = function() foo = 1 end
Thanks for this question since it makes it clear why nil is so dangerous. The simple solution is:
local bar = function()
local foo = bar()
Removing nil forces to provide a value at variable declaration, so the line "local foo" is not valid anymore. Since the algorithm used to initialize the variable is in bar, we just change the API for bar to return the result that will be used to initialize foo.
Your example is really good to probe the "madness" of nil.
Imagine that we are working with a complex 10k lines of code and later on we have some code looking like:
if foo == nil then
With the first version of the code (nil allowed), if we forgot by mistake to invoke bar() we will be much poorer now :( .
In the second version of the code, If we remove the nil, we are forced to initialize foo before using it. If we forget to execute " foo = bar()" the line "if foo == nil" will fail with an error similar to "foo is undefined".
A very illustrative example of the billion-dolar-mistake.
I will try to find some time to create a nil-free implementation based on the existing code, and publish it on GitHub. Anyone curious is welcome to participate. Since I don't have much free time I can not promise anything in the coming month/s.
(Sorry if I do not reply to all your comments, but I don't have time enough to do it, even if some are really interesting)