Lua: understanding part of a table array and hash part

There is also an example in Section 4, “Tables,” in “Implementing Lua 5.0”:
local t = {100, 200, 300, x = 9.3}

So we have t[4] == nil . If I write t[0] = 0 , this will go into the hash part .
If I write t[5] = 500 , where will it go? Part of an array or hash part ?
I would like to hear the answer on Lua 5.1, Lua 5.2 and LuaJIT 2 if there is a difference.

+4
source share
2 answers

Adjacent integer keys starting with 1 always go to parts of the array.

Keys that are not integer positive always go in the hash part.

Other than that, it is not specified, so you cannot predict where t[5] will be stored in accordance with the specification (and it may or may not move between them, for example, if you create, then delete t[4] .)

LuaJIT 2 is slightly different - it will also store t[0] in an array.

If you want it to be predictable (which is probably a designer smell), stick to pure array tables (adjacent integer keys starting at 1 - if you want to leave a space, use false instead of nil ) or clean hash tables (avoid non-negative integer keys.)

+2
source

Quote from the Lua 5.0 implementation

Part of the array tries to store values ​​corresponding to integers from 1 to a certain limit n. Values ​​corresponding to non-integer keys or integer keys outside the range of the array are stored in the hash part.

The index of the array part starts at 1, so t[0] = 0 will go to the hash part.

The calculated size of the part of the array is the largest, since at least half of the slots between 1 and n are used (to avoid loss of space with sparse arrays), and there is at least one interval used between n / 2 + 1 and n (to avoid size n when n / 2 will do).

According to this rule, in the table of examples:

 local t = {100, 200, 300, x = 9.3} 

The part of the array that contains 3 elements can be 3, 4, or 5. (EDIT: size must be 4, see @dualed comment.)

Suppose the array has size 4, when writing t[5] = 500 part of the array can no longer hold the element t[5] , what if the size of the array changes to 8? At size 8, part of the array contains 4 elements that are equal (so, at least) to half the size of the array. And the index from n / 2 + 1 to n, which in this case is 5-8, has one element: t[5] . Thus, the size of array 8 can fulfill this requirement. In this case, t[5] goes to the part of the array.

+1
source

Source: https://habr.com/ru/post/1490702/


All Articles