First, let's look at the source code for obtaining the length of a Lua table (ltable.c)

j is the length of the array part. First, if the array length is greater than 0 and the last element of the array is nil, use binary search to find and return the length.

If t->node stores the hash part of the table, and if it is empty, return the length of the array.

First example:

In this case, the array length is initialized, and the length of t is 7. Why? Because the last element is not nil.

In the following case, the length of t is 5.

Second example:

Everyone should know that the length of t is 5.

In this case, what is the length of t???

The answer is 2. Why?

The insertion of t

t

Then it will enter (lvm.c)

Then it will call the function luaH_newkey in (ltable.c)

Then it calls rehash

This part is actually the calculation of the array part and what goes into the hash part. nums is the distribution of statistics. If you look carefully at the code, you will know that the array length is 2 to the power of n.

Here, nil is not a number and is not included in the statistics, so 1, 2, 5, and 6 will calculate the array length as 4, and the rest will be placed into the node part.

A table is composed of an array and a node hash part.

Thus, according to the function we looked at earlier, the fourth one is nil, so the length found using binary search is 2.

This is a pitfall that may be caused if there is nil in a Lua array. Of course, it is only caused by rehash.

Original address: https://www.cnblogs.com/wallini/p/4188499.html