How does Lua's table length operator work?
<p>Can someone explain this apparent insanity?</p>

<pre><code>&gt; t = {1, 2, 3} -- Table length 3. Simple
&gt; = #t
3  -- Yep

&gt; t[3] = nil -- Remove the last element?
&gt; = #t
2 -- Ok it realises it is the last one (since #t = 3) and decrements the length

&gt; t[6] = 6 -- Add a separate element?
&gt; = #t
2 -- Ok... I guess? Although surely it knew #t = 2, and so now #t should be 6?

&gt; t[4] = 4 -- Add another separate element
&gt; = #t
4 -- Errr... what.

&gt; t[5] = 5 -- Append another element
&gt; = #t
6 -- Ok now it remembers element 6? Wtf?
</code></pre>

<p>Ok let me try again...</p>

<pre><code>&gt; t = {1, 2, 3}
&gt; = #t
3
&gt; t[10] = 10
&gt; = #t
3
&gt; t[4] = 4
&gt; = #t
4
&gt; t[9] = 9
&gt; = #t
4
&gt; t[8] = 8
&gt; = #t
10
</code></pre>

<p>What.</p>