[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Deprecate "Attempt to index a nil value" error; instead, return nil or create table
- From: Philippe Verdy <verdyp@...>
- Date: Sun, 1 Mar 2020 16:46:04 +0100
If such behavior is added, it should depend on a table's
meta-property, i.e. a special value in its metatable.
Autocreation can also create problems in Lua.
Or may be there's a need to subclass the "nil" value: reading an
unassigned position in a table with this property could return this
special "niltable" value (whose type/class would be the same as nil)
but which differs from "nil" by the fact that "niltable" is indexable
like a table but will not throw an error when subindexing it for
further reads or writes and would behave as a no-op.
Basically "niltable" and "nil" would still be equal for "==" but
distinct for identity, and they would both by of type "nil":
nil==niltable and typeof(nil)=="nil" and typeof(niltable)=="nil".
And unlike "nil", "niltable" would have a metatable containing the
array-indexing meta-operator functions. "niltable" would not be
modifiable/mutable at all.
A table that must not throw an error, and "niltable" itself, would
just both have to contain the same meta-operators to override the
default error-throwing behavior.
Le dim. 1 mars 2020 à 16:28, Anton Jordaan <firstname.lastname@example.org> a écrit :
> >> Italo Maio wrote:
> >> Perl has auto-vivification and it creates way more problems than it
> >> solves. Also agree this should not be part of the language and the
> >> error when trying to index a null value is a good thing.
> I am not very familiar with Perl, but AFAIK, Perl's auto-vivification
> automatically creates array elements even when just *reading* from the
> This is not what I suggest Lua should do. Lua should only create tables
> when *assigning*. When reading, just return nil and don't create anything.
> > Soni "They/Them" L. wrote:
> >> > v = (pcall(function() t[a][b][c][d][e] end) or nil) and
> >> t[a][b][c][d][e]
> This will work, and there are indeed multiple ways to code v =
> t[a][b][c][d][e] to avoid throwing an error.
> To the best of my knowledge, the code example that posted (with lots of
> "and"s), executes the fastest (and is also relatively easily readable).
> > Coda Highland wrote:
> >> This comes up very, very frequently.
> >> This is absolutely a non-starter for inclusion in stock Lua, but for
> >> your own programs there are a number of solutions that have been
> >> proposed and/or implemented.
> Could you elaborate why this is a non-starter?
> I have seen a number of solutions (including solutions that use
> metatables to define dynamic arrays, which are useful only when
> assigning) and also offered my own preferred code examples,
> which manage do the job in my own programs, but none of these
> workarounds are as simple -- and consistent -- as writing v =
> -- Anton