Lua Table Length Analysis
Category Programming Techniques
Let's first look at the part of the Lua table source code for obtaining the length (ltable.c).
j is the length of the array part. First, it checks whether the array length is greater than 0, and the last one is nil, then it uses binary search to find and return the length.
If t->node is where the table's hash part is stored, if it's empty, it returns the length of the array.
First example:
For this case, the array length is initialized, and the length of t is 7, why is that? Because the last position is not nil.
In the following situation, the length of t would be 5.
Second example:
Everyone should know that the length of t is 5.
So, what is the length of t here?
The answer is 2, why is that?
The insertion of t[6] causes the table to rehash.
t[6] will first call (lapi.c)
Then it will enter (lvm.c)
Then it will call (ltable.c) the luaH_newkey function
Then it calls rehash
This part is actually the calculation of the array part and the part put into the hash part, nums is the distribution of statistics, and by looking at the code carefully, you will know that the array length is 2 to the power of n.
Here, nil is not a number and will not be included in the statistics, so 1, 2, 5, 6 will calculate the array length to be 4, and the rest will be put into the node part.
The table is composed of an array and a node hash part.
So according to the function we saw earlier, the fourth one is nil, so the length found by binary search is 2.
This is a pitfall in the Lua array if there is a nil, of course, it is only caused by rehash.
>
Original article: https://www.cnblogs.com/wallini/p/4188499.html
** Click to share notes
-
-
-