3 ms·
Lua is actually closer to PHP in how arrays are used in it. "Until Lua 4.0, tables were implemented strictly as hash tables: all pairs were explicitly stored.
by dchest 15y ago
Lua is actually closer to PHP in how arrays are used in it.
"Until Lua 4.0, tables were implemented strictly as hash tables: all pairs were
explicitly stored. Lua 5.0 brought a new algorithm to optimize the use of tables
as arrays: it optimizes pairs with integer keys by not storing the keys and storing
the values in an actual array. More precisely, in Lua 5.0, tables are implemented
as hybrid data structures: they contain a hash part and an array part. Figure 2
shows a possible configuration for a table with the pairs "x" → 9.3, 1 → 100,
2 → 200, 3 → 300. Note the array part on the right: it does not store the integer
keys. This division is made only at a low implementation level; access to table
fields is transparent, even to the virtual machine. Tables automatically and dy-
namically adapt their two parts according to their contents: the array part tries
to store the values corresponding to integer keys from 1 to some limit n. Values
corresponding to non-integer keys or to integer keys outside the array range are
stored in the hash part.
When a table needs to grow, Lua recomputes the sizes for its hash part and
its array part. Either part may be empty. The computed size of the array part
is the largest n such that at least half the slots between 1 and n are in use
(to avoid wasting space with sparse arrays) and there is at least one used slot
between n/2 + 1 and n (to avoid a size n when n/2 would do). After computing
the new sizes, Lua creates the new parts and re-inserts the elements from the
old parts into the new ones. As an example, suppose that a is an empty table;
both its array part and hash part have size zero. If we execute a[1]=v, the table
needs to grow to accommodate the new key. Lua will choose n = 1 for the size
of the new array part (with a single entry 1 → v). The hash part will remain
empty."
From "Implementation of Lua 5.0" -- http://lua.org/doc/jucs05.pdf http://lua.org/doc/jucs05.pdf