lua-users home
lua-l archive

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


On Sun, May 09, 2010 at 04:49:53PM +0100, Peter Cawley wrote:
> > Could indexing anything but a table, or at least indexing nil,
> > return nil instead of throwing an error?
> > I don't see why x.z conveniently gives nil, if there is no z in x,
> > but x.y.z requires an extra check for x.y .
> > This makes working with structures with lots of optional parts pretty
> > tedious - and if it's external input, basically everything is optional.
> 
> If you want this, then you can already get it in 5.1 by doing:
> debug.setmetatable(nil, {__index = {}})

I was considering this,
yet then I would have empty tables showing up when using
a nonexistent string value,
and I'd be confined to rawget to really check wether it exists.

I think it's more about the behaviour of the operation
and more precisely type coercion regarding nil:
does the error make that much sense after all?

Ok, the proposal for "indexing anything but a table" was
not that serious, but wrt to nil, I'd say if you expect
an error from x.y.z, if there is no y in x
- or from y.z, if there is no y in _G, for that matter -
then you'd also want an error from x.z, if there is no z,
or from y, if there is no y in _G.

And that, indeed, can be achieved using __index,
and those who like errors use that approach on _G.
But that is not how Lua does it by default.

Oh and sorry bout the typo :)


best
Klaus