• Subject: Re: Why is nil not a valid table key?
• From: Chris Marrin <chris@...>
• Date: Sun, 27 Nov 2005 10:27:27 -0800

```Rici Lake wrote:

```
```
On 27-Nov-05, at 12:52 PM, Chris Marrin wrote:

```
It is pretty easy to store a 'length' property in a table to identify how many numeric keys it has.
```

```
Sure. I think Mike was talking about the general iteration case, though, not the numeric one.
```
```
I found that technique ALMOST works in Lua. If a table has entries for numeric keys 1,2,12 and 17, and I set the length property to 17 then I can go:
```
for i=1,t.length do
print(t[i])
end

```
and I will get all the numbers printing out, with nils in the slots that don't have a numeric index.
```

In fact, that's the way it was at one time (with 'n' in place of 'length').

```
```
But I found that attempting to set:

t[0] = "hello"

```
does not work. When I read this back, it prints nil. Is this true, or do I have a bug in my logic somewhere?
```

You have a bug in your logic somewhere.

Lua 5.1 (beta)  Copyright (C) 1994-2005 Lua.org, PUC-Rio
> t = {}
> t[0] = "Hello"
> =t[0]
Hello

Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
> t = {}
> t[0] = "Hello"
> =t[0]
Hello
```
```
Hmmm. Ok, thanks for doing the test!!!

--
chris marrin              ,""\$, "As a general rule,don't solve puzzles
chris@marrin.com        b`    \$  that open portals to Hell" ,,.
,.`           ,b`    ,`                            , 1\$'
,|`             mP    ,`                              :\$\$'     ,mm
,b"              b"   ,`            ,mm      m\$\$    ,m         ,`P\$\$
m\$`             ,b`  .` ,mm        ,'|\$P   ,|"1\$`  ,b\$P       ,`  :\$1
b\$`             ,\$: :,`` |\$\$      ,`   \$\$` ,|` ,\$\$,,`"\$\$     .`    :\$|
b\$|            _m\$`,:`    :\$1   ,`     ,\$Pm|`    `    :\$\$,..;"'     |\$:
P\$b,      _;b\$\$b\$1"       |\$\$ ,`      ,\$\$"             ``'          \$\$
```"```'"    `"`         `""`        ""`                          ,P`

```