How not to turn an array into a hash in lua (prevent an array from becoming a hash)?

If I write in Lua

local var = {1,2,3,4,5,6}

      

The var variable is an array.

If I want to store it as an array (not a hash), I have to use table.insert, table.remove, etc.

This code will turn it into a hash:

var["key"] = 4

      

Question: Does this code turn an array variable into a hash?

local var = {1,2,3,4,5}
var[4] = "string"
var[6] = "string"
var[1] = "string"

      

+3


source to share


2 answers


As others have already pointed out, Lua only has tables. Internally, the values ​​you put into a table can be stored in an array or hash part of it, but this is an implementation detail that users don't need to worry about.

In your specific case, the keys will only be stored in the part of the array (even after being assigned), since you are not creating any new keys. As detailed in the Lua Performance Tips (About Tables section), the initial assignment will allocate 6 slots in the array, and then you just reinstall them. If you add var[7] = "string"

, this value will go into the hash part, and this will cause a re-hash, since the hash part is 0 at this point. Lua will calculate how many slots are needed to fit all the values ​​in the part of the array (now 7) and "chooses the largest array size of 2 so that more than half of the array's elements are filled." Now the part of the array will have 8 slots, and the hash part will have size 0 since there are no elements there.

QUESTION: Does this code turn an array variable into a hash?



So the answer to this question is "no" (if "turn to hash" means the table receives a non-zero hash portion). If you do var[8] = "string"

(no assignment var[7]

) the hash part will get a nonzero size, but if you do later var[7] = "string"

it will cause a different re-hash as that element will not fit into the hash part and all these elements will be assigned to the array part again.

Lua tries its best to preserve the most appropriate structure for the elements you have in the table, but changes to the structure itself are only done during re-hashing.

+2


source


You are trying to distinguish between "arrays" and "hashes" which Lua does not. They are all tables. Some of them just have keys that are not integers.



+1


source







All Articles