lua-users home
lua-l archive

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


On Thu, Jul 21, 2016 at 6:08 PM, Luiz Henrique de Figueiredo
<lhf@tecgraf.puc-rio.br> wrote:
>> The first use case that came to mind was JSON deserializers, where the
>> obvious mapping of null to nil causes problems with arrays.
>
> That's the whole point: one probably shouldn't not force the semantics
> of one language into another. In this case, and others, it's simpler
> and clearer to define
>         null = {}
> once and use it where needed. if you must skip over these when traversing
> a table, then that's what your semantics dictates and you must do it.
> Just do not try to do this with nil, which has its own, clear semantics
> in Lua.

I think part of the reason people try to use Lua's `nil` in ways like
JSON's `null` or Python's `None` is because, in a context where you
know you won't get the Boolean `false`, `if var then ...` is an easy
way to check if `var` is a useful value or not, as `nil`, `null`, and
`None` all evaluate to false in a Boolean context.

The problem arises when one tries to create a singleton to represent
this lack of a useful value. Python provides the `__bool__` method (in
3.x; `__nonzero__` in Python 2.x) to customize the behavior of an
object when used in a Boolean context. Lua does not provide any such
metamethod, for either tables or userdata, so any user-created
singleton is automatically true in a Boolean context. This means that
the idiom `if var then ...` no longer works, and an explicit
(in)equality check against the singleton is required, creating uglier
code.

Perhaps what Lua *really* needs to solve this problem, then, is a
__bool metamethod that, if present, is called when the object is used
in a boolean context (such as `if`, `and`, and `or`) and returns
either true or false, replacing the default true. Then one can take
these `null` singletons and slap a `{__bool = function(t) return false
end}` metatable on them, allowing them to gain the benefits of `nil`
without the drawback of `nil`.

What does everyone else think about a __bool metamethod?