Correct, Kored, you can't:
Code:
> r = {}
> r[12] = 12;
> =r.12
stdin:1: '<eof>' expected near '.12'
Now, also note this: foo["bar"] and foo.bar are
completely identical. It's up to you which way to use, but there is no benefit of one over the other (other than for readability purposes -- if you want to get more complicated, one method does imply something where the other does not with regards to OOP, but that's another story... if you want, read my article at
http://www.wowwiki.com/Object_Oriented_Programming ).
Another thing to note is that if you are going to be skipping entries, you start using a hash table, not an indexed table. Thus:
Code:
> c = {}
> c[1] = 1;
> c[2] = 2;
> = #c
2
> c[10] = 10;
> = #c
2
> c[5] = 5;
> = #c
2
> c[4] = 4;
> = #c
10
> = c[6]
nil
So some strange things start happening
Technically for these tables, the length operator # is undefined, but that's probably not your concern. What IS your concern is this:
Code:
> collectgarbage"stop"
> foo, bar, gc = {}, {}, 0 -- Allocate before counting GC
> gc = collectgarbage"count"
> for x = 1, 100 do
>> foo[x] = x;
>> end
> print(collectgarbage"count"-gc)
4.443359375
> gc = collectgarbage"count"
> bar[1] = 1;
> bar[100] = 100;
> for x = 2, 99 do
>> bar[x] = x;
>> end
> print(collectgarbage"count"-gc)
4.91015625
The tables are stored differently, and that's something you should keep in mind. Hash tables (which the becomes) are almost always bigger than indexed tables, so pay attention how you're creating the table. A lot of factors come into play. But Lua will always try to find the optimal way to create the table
at the time, which may be an indexed table, depending on where you're doing it. Remember the powers of two? See:
Code:
> collectgarbage"stop"
> foo, bar, gc = {}, {}, 0
> gc = collectgarbage"count"
> for i = 1,16384 do
>> foo[i] = i;
>> end
> print(collectgarbage"count"-gc)
259.2587890625
> gc = collectgarbage"count"
> for i = 1,10000 do
>> bar[i] = i;
>> end
> bar[16384] = 16384;
> for i = 10001, 16383 do
>> bar[i] = i;
>> end
> print(collectgarbage"count"-gc)
261.029296875
vs.
Code:
> collectgarbage"stop"
> foo, bar, gc = {}, {}, 0
> gc = collectgarbage"count"
> for i = 1, 16384 do
>> foo[i] = i;
>> end
> print(collectgarbage"count"-gc)
259.26171875
> bc = collectgarbage"count"
> gc = collectgarbage"count"
> for i = 16384, 1, -1 do
>> bar[i] = i;
>> end
> print(collectgarbage"count"-gc)
258.7421875
> baz = {}
> gc = collectgarbage"count"
> for i = 1,16384,4 do
>> baz[i] = i;
>> end
> for i = 2,16384,4 do
>> baz[i] = i;
>> end
> for i = 3,16384,4 do
>> baz[i] = i;
>> end
> for i = 4,16384,4 do
>> baz[i] = i;
>> end
> print(collectgarbage"count"-gc)
266
So it can vary depending on when and how it's created. Always keep that in mind. And I'll shut up now, I think I've thrown too much information your way
EDIT: Not stopping GC produces strange results