lua-users home
lua-l archive

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


2014-05-17 18:38 GMT+02:00 Andrew Starks <andrew.starks@trms.com>:
> If you set the nil metatable to return nil (thanks for the bug report in my
> example)  then all kinds of helpful errors dissapear.
> I played with this for a bit and productivity tankened.
> As is, Lua doesn't have a more terse/clear way than:
>
> if a.b and a.b.c.d and a.b.c.d.e then
> ...
>
> In this example, the op is looking for:
> if a.b?c.d?e then
> ...
>
> Where a==nil would error.
>
> This is something that I would think would make code clearer.

I can do this: Use `/` instead of `.`, but put `//` instead after the
first field that must exist.

It's possible in Lua 5.2 too, of course, with __mul or __mod
instead of __idiv.

Field names must not be global variables or start with underscore.

Lua 5.3.0 (work2)  Copyright (C) 1994-2014 Lua.org, PUC-Rio
> require"query"
Query hack enabled
> a={b={c={d={e='bazinga'}}}}
> a/b/c/d/e
bazinga
> a//b/c//d/e
bazinga
> a/b/g/d/e
nil
> a//b/g/d/e
nil
> a/b//g/d/e
nil
> a/b/g//d/e
./query.lua:4: attempt to index a nil value (local 'a')
stack traceback:
    ./query.lua:4: in function '__idiv'
    stdin:1: in main chunk
    [C]: in ?
> a/b/g/d//e
./query.lua:4: attempt to index a nil value (local 'a')
stack traceback:
    ./query.lua:4: in function '__idiv'
    stdin:1: in main chunk
    [C]: in ?
>