lua-users home
lua-l archive

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


I’ve used some strongly typed languages that have a “try operator”. I think lua could use something similar.
In this case something like t?[a]?[b]?[c]?[d]?[e], would be equivalent to t[a][b][c][d][e], but if any evaluation preceded by a ? has a false value (false or nil), the result of the entire _expression_ is that value (short circuiting). This only short circuits out of chains of index expressions (of all forms), and function calls. Would that be something that would work in lua?

On Sat, Feb 29, 2020 at 13:07 Soni "They/Them" L. <fakedme@gmail.com> wrote:


On 2020-02-29 1:56 p.m., Philippe Verdy wrote:
> I see no value at all in adding "or nil" (except that you'll change a
> "false" stored value, returned without exception, into an "nil"). Then
> why do you need "and t[a][b][c][d][e]" ? Wouldn' this be enough?:
>
>   _, v = pcall(function() return t[a][b][c][d][e] end)
>
> i.e. discard (_) the false/true status in the 1st return value of the
> pcall, use the second value which is explicitly returned and will be
> nil if the function does not return but throws an exception.

actually it'll be the string "attempt to index a nil value"

>
> Le sam. 29 févr. 2020 à 17:43, Soni "They/Them" L. <fakedme@gmail.com> a écrit :
> >
> >
> >
> > On 2020-02-29 1:31 p.m., Egor Skriptunoff wrote:
> > > On Sat, Feb 29, 2020 at 5:42 PM Italo Maia wrote:
> > >
> > >     the error when trying to index a null value is a good thing.
> > >
> > >
> > >
> > > Let's assume the statement
> > > v = t[a][b][c][d][e]
> > > Each of 5 indexing steps might result in nil.
> > > Sometimes you want to raise "Attempt to index a nil value" exception,
> > > sometimes you want to ignore the exception.
> > >
> > > If nil is indexable, then it's pretty easy to raise the exception
> > > v = assert(t[a][b][c][d])[e]
> > >
> > > But if nil is non-indexable, it's not easy to ignore the exception
> > > v = (((((t or {})[a] or {})[b] or {})[c] or {})[d] or {})[e]
> > >
> > > Indexable nil looks like a better alternative.
> > >
> > > Would indexable nil reduce runtime error detection?   No.
> > > Almost always another exception will be raised soon:
> > > "Attempt to perform arithmetic on a nil value" and the like.
> > >
> >
> > v = (pcall(function() t[a][b][c][d][e] end) or nil) and t[a][b][c][d][e]
> >
> > slightly cleaner.
> >
>