lua-users home
lua-l archive

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


It was thus said that the Great Jonathan Goble once stated:
> 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.

  In my CBOR [1] library [2], it returns nil for 'null' and 'undefined' by
default, but that can be overridden by the user (in fact, just about
everything can be overridden by the user) so to me, that's more a limitation
of the JSON module than of actual problems with semantics.  If you care
enough, you'll make the distinction.

> 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?

  A __boolean metamethod was mentioned?  Proposed?  I'm not sure, but in any
case, one was mentioned here:

	http://lua-users.org/lists/lua-l/2011-12/msg00621.html

but it seems like it was for something else.

  -spc (Keeper of the metamethod proposals ... )

[1]	Concise Binary Object Representation, RFC-7049

[2]	https://github.com/spc476/CBOR