I'm new to Lua, and I'm learning the usage of table these days. From tutorials I know that Lua treats numeric indexed items and non-numeric indexed items differently, so I did some tests myself, and today I found an interesting phenomenon and I can't explain it:
The code
t = {1, 2, 3, a='a', b='b'}
print(#t)
gets
3
because the #
operator counts numeric indexed items only. Then I tested the following code
t = {1, 2, 3, a='a', b='b'}
print(#t)
for i = 100,200 do
t[i] = i
end
print(#t)
I get
3
3
Till now I think Lua treats those discontinuous items added later as non-numeric indexed ones. However, after I change the code a little bit
t = {1, 2, 3, a='a', b='b'}
print(#t)
for i = 100,300 do
t[i] = i
end
print(#t)
I get
3
300
I'm confused by this phenomenon, does anyone know the reason? Thanks.
(This phenomenon can be reproduced at http://www.lua.org/cgi-bin/demo)
Update:
I tried this code
t = {1, 2, 3, a='a', b='b'}
print(#t)
for i = 100,300 do
t[i] = i
print("add", i, #t)
end
for i = 100,300 do
t[i] = nil
print("del", i, #t)
end
I get
3
add 100 3
add 101 3
add 102 3
...
add 223 3
add 224 3
add 225 3
add 226 226
add 227 227
add 228 228
...
add 298 298
add 299 299
add 300 300
del 100 300
del 101 300
del 102 300
...
del 253 300
del 254 300
del 255 300
del 256 3
del 257 3
del 258 3
...
del 298 3
del 299 3
del 300 3
This example shows that Lua does convert a table between sparse and dense.