lua-users home
lua-l archive

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


> Now, how do you imagine these functions:
> 
> 1. a consumer that is not guaranteed to have data available, like a
> nonblocking socket. Today it is
>     data, err = read()
> If data is nil that means that read() could not actually read
> anything, so can not provide a value. Depending on how read() works,
> an error message could be useful or not. In the simplest case no
> error message is needed: no data means no data, do whatever you can.
> 
> 2. A function that returns a boolean:
>     __eq = function (a, b) return a == b  end
> There is nothing special in returning a false.

Actually there is. If 'read' can return 'false', you cannot use
'assert(read(...))' to check that no errors occurred.

But that is not relevant here. What is relevant is that, if 'read'
can read *anything*, of course it should be able to read 'nil',
too. (Otherwise, how could it return the result of a query like "what
was the result of the last call to 'read'" where that last call failed?)

The key point is: you cannot use a value to represent the absence of
a value, at least not as a generic methodoly.

So, if you need to return any value + error, you need more than one
value (like 'pcall' does) or some other mechanism besides returns (like
'error'). That is a fact of life, and we are not going to solve it
by throwing more values/non-values/semi-values/error-values into the
language.

If you want a one-size-fits-all sollution, you usually choose "more
than one value" (as Go does) or exceptions (as Python does). In Lua, we
are more pragmatic, and prefer not to use one-size-fits-all sollutions.
Most cases can be handled in simpler ways. [1]

My point is that, in the simpler and more common case when the function
cannot return nil nor false and returns a message, false-msg might be
better than nil-msg.


[1] There is a difference between assuming that your average programmer
is ignorant ("lacking knowledge, information, or awareness about
something in particular") and assuming that he is stupid ("slow to
learn or understand; obtuse.")  (I am not sure why I wrote that...)

-- Roberto