lua-users home
lua-l archive

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

On Wednesday, January 14, 2015, Jorge <> wrote:
On 14/01/15 16:28, Roberto Ierusalimschy wrote:
So, if the first return is nil, you should be able to safely assume
that there won't be anything of interest after that. Except an
You got my point, except about your "except" :-) If the first return is
nil, you should be able to safely assume that there won't be anything of
interest after that. Period.

-- Roberto

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.


[It is weird to be defending an idea in front of it's author.]

Consider a convention where a function returns the requested value, always. If it cannot, it does not return and instead errors (or it is a bug). That is, functions return one kind of value, not "the value you want or a reason why that couldn't happen."

There is no issue with sentinel values or other tea leave reading. 

The negative of this is that when you want to trap a particular error, because you know how to handle it, you use pcall[1], but in my short experience, this ends up being in only a couple places in the code. 

The library author does not know the stack position that will handle the error and so `nil, error` often causes more code than not. Passing `nil, error_msg` back up the stack was everywhere in my code, before this change.

So, of course I've written this before and 0 people like this approach. I have not been able to understand why this is the case even as it has worked for me.

I'm happy to be weird, but I'm missing something that experience has yet to teach me?

Do people to to conceive of think of "error" as something dire and to be avoided always?

If there were any additions to Lua around this topic, then I'd be excited to see more capability/flexibility/common patterns with `error` and error messages. 


[1]In the case of `nil, error_string`, you can achieve this same effect by wrapping the call around `assert`, except that the stack is moved and that might matter.