lua-users home
lua-l archive

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


On 25 April 2017 at 03:31, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 2017-04-24 18:32 GMT+02:00 Roberto Ierusalimschy <roberto@inf.puc-rio.br>:
>
>> If there are no results to be returned, it returns nothing.
>
> This is a good habit to follow. I have noticed "return nil" in some
> published code, some of which may even be mine. I'll be more
> watchful from now on!

Using `return nil` is not a code smell. Please do not turn a specific
use-case into a blanket recommendation that turns into a cargo-cult.
Returning an explicit nil is a perfectly fine marker for error
conditions, it is not "considered harmful". In case you need an
appeal-to-authority to be convinced of that, Roberto does it in the
return of string.find() when a match is not found. One could just as
well make the case that in string.find("hello", "a") there are no
results to be returned (nothing was found by the 'find` function,
after all), but that function returns an explicit nil — so in the end
that observation would still be open to interpretation by the API
author.

A more specific recommendation that matches the use-case of
string.byte is to return nothing in functions with variadic results
when the arity of the return is 0. Note that this is also the result
we nicely get when we use an idiom such as `return
table.unpack(results)`.

-- Hisham