  lua-l archive

• Subject: Re: Deprecate "Attempt to index a nil value" error; instead, return nil or create table
• From: Anton Jordaan <anton.jordaan@...>
• Date: Tue, 3 Mar 2020 13:52:23 +0200

```Sean Conner wrote:
```
```Here are some of the issues that need to be addressed for this to work.
1) t[a] = v This is syntactic sugar for t = { [a] = v }.  Then does that mean:
local t[a] = v is legal
```
```Yes, local is legal.

```
```2) t[a][b][c][d][e] = v -- when t[a][b] exists
An asusmption being made is that a,b,c,d,e are all tables.  They
don't have to be.  It could be a userdata that responds to both
__index and __newindex to act like a table.  Then this is fine, but
what if b*doesn't*  respond to __newindex?
```
a,b,c,d,e can be any valid table indices.  I assume you meant "what if t[a][b] doesn't respond to __newindex"?
```
```
Since t[a][b][c][d][e] = v is simply syntactic sugar, it should expand to the following, and will throw the same errors: (assuming in this case that the interpreter finds that t[a][b] already exists)
```
t[a][b][c] = {[d] = {[e] = v}}

If t[a][b] exists but doesn't respond like a table, an error will be thrown.

```
```3) v = t[a][b][c][d][e]

v ends up nil.  Which index is nil?
```
```The nil return value will not provide this information.

```
```4) Also, what about: t[a],t[b],t[c] = 1,2,3 How does this play out, syntactic surgar wise?
```
Although my proposal has more to do with multi-dimensional arrays, the same can be applied to new one-dimensional tables. If t is undefined, the above unambiguously means that t is intended to be a table, so following the principle that "When writing: automatically assign a single-entry table to each undefined variable, with the given index the sole entry", we get:
```t = {[a] = 1}
t[b] = 2
t[c] = 3

```
```4) t[a] [ t[B] ] [c][d][e] = v
If t doesn't exist, then what do we end up with?  If B doesn't
exist, what do we end up with?  It's hard to think about.
```
This should throw an "table index is nil" error, since t[B] is nil, and therefore an invalid index for assignment. N.B.:  My proposal is not that nil or NaN should become valid table indices, and my "syntactic sugar for autovivification" (if I may borrow the Perl term) will only apply when the indices are valid, and only when assigning, not when reading.
```

```
```5) t[a][0/0][c][d][e] = v
The previous question brings this up---what if the index is NaN?
Rare, but possible.  Treat it as nil?  Error?
```
As in question (4), this should throw an error, since it is an assignment to an invalid index.
```
```
Currently, Lua throws an error when assigning to an invalid index (nil or NaN), but returns nil when reading from the same:
```t[0/0] = 1 throws "table index is NaN" error,
v = t[NaN] just returns nil.

```

• Follow-Ups: