Table processing and precautions for Lua

Source: Internet
Author: User
Tags integer numbers

Lua is a very lightweight and nice scripting language. As the most frequently used table in Lua, Lua still has many advantages and disadvantages;

The following is a blog about Lua table by Daniel Yunfeng, which can be used to gain a glimpse of the internal mechanism of Lua table;

The overall efficiency of Lua is very high, and its Table Implementation cleverly contributes a lot to this efficiency.

The Lua table acts as an array and a ing table. Therefore, this is taken into account during implementation, so that the table can be used as little as possible for Array usage.

Lua does this. It divides a table into two parts: array segment and hash segment. The numeric key is generally placed in the array segment, and all key values that have not been initialized are set to nil. When the numeric keys are too discrete, some of the larger numeric keys are moved to the hash segment. This split line is based on the utilization rate of the array segment not lower than 50%. When the values of 0 and negative values are key, they must be placed in the hash segment.

String and number are put together for hash, respectively, with their own algorithms, but the hash results are all in a numerical segment. The hash segment adopts the closed hash method, that is, all values exist in the table. If a hash collision occurs, additional data is stored in the idle slot without additional space. When the entire table is full, the hash segment will expand, and the data in all segments will be re-hashed. After re-hash, the conflict will be greatly reduced.

This table implementation policy ensures the search efficiency first. When using the table array, it will be as efficient as the C array. For the value of the hash segment, searching is almost the process of calculating the hash value (where the hash value of string is calculated and saved in advance ), there is only a little extra search time during the collision, and the space will not be too wasted. When the hash table is full, insertion is prone to collision. In this case, an empty slot needs to be found in the table. In the table structure, Lua records a pointer sequentially inserted from one end to the other to solve the empty slot search. Each slot points record the next pointer to save the relevance of the key to be collided.

In general, this solution is very good.

I did some research on the implementation of ing tables some time ago. Paste it on the message book:
<A href = "http://www.codingnow.com/2004/board/view.php? Paster = 777 & reply = 0 "> A ing table that combines tree tables </a>
<A href = "http://www.codingnow.com/2004/board/view.php? Paster = 776 & reply = 0 "> strike a balance between vector, map, and list </a>

Link: http://blog.codingnow.com/2005/10/lua_table.html

 

Even for coder, which has been developed for quite a long time as Lua, it is not clear that many things are not discussed in person. The length problem of Lua table is a wonderful example; you may not be very clear about the following;

There are several ways to get the Lua table length: Table. getn (table_name), # table_name, table. maxn (table_name), coupled with ipairs (table_name) and pairs (table_name) traversal;

According to the articles written by Yunfeng, we can know that Lua's two different storage methods are naturally different from the previous methods for obtaining the Lua table length;

Table. maxn (table)

Table. the maxn () function returns the maximum value of all positive key values in the specified table. if no element with a positive key value exists, 0 is returned. this function is not limited to the array part of the table.

Table. getn (table)
Returns the number of elements in the table.

# (Table)

The returned length is the number of consecutive integer numbers (or the default integer) in the Lua table;

The pairs () function is basically the same as the ipairs () function. The difference is that pairs () can traverse the entire table, including arrays and non-arrays.

About the Lua table length problem, the http://blog.csdn.net/dssdss123/article/details/12676329 for some wonderful issues or some in-depth; test [Lua version = 5.1.4], indeed so;

However, there are still some things that need to be supplemented. For the # usage, its performance and table. getn () is similar in many extreme cases; table. maxn (), because it obtains the maximum key value among all positive key values in the table. discontinuous;

local tblTest ={    "this 1",    "this 2",    [3] = 2,    [4] = 5,    [5] = 7,    "this 3",    [10] = 10,}print(table.getn(tblTest))print(#(tblTest))print(table.maxn(tblTest))--===========================>lua -e "io.stdout:setvbuf ‘no‘" "filedeal.lua" 5510--===========================local tblTest ={    "this 1",    [3] = 2,    [4] = 5,    [5] = 7,    "this 3",    --"adsfasd",    [10] = 10,}print(table.getn(tblTest))print(#(tblTest))print(table.maxn(tblTest))--===========================>lua -e "io.stdout:setvbuf ‘no‘" "filedeal.lua" 5510--===========================local tblTest ={    "this 1",    [3] = 2,    [4] = 5,    [5] = 7,    --"adsfasd",    [10] = 10,}print(table.getn(tblTest))print(#(tblTest))print(table.maxn(tblTest))--===========================>lua -e "io.stdout:setvbuf ‘no‘" "filedeal.lua" 1110--===========================    

The difference between the preceding three tabtests is that the default table of Lua is from 1 and there are two default tables, so that [3] = 2, this element is sufficient to connect continuity, when it cannot be connected, the printed values are different because of the discontinuous rows;

If a new NIL is written after or in the table, the output content is different: SO ~Do not use the nil value in the Lua table. If an element is to be deleted, remove it directly. Do not use nil instead.

What if we add a default element in the table below after the element? Sample Code:

local tblTest ={    "this 1",    [3] = 2,    [4] = 5,    [5] = 7,    "this 3",    --"adsfasd",    [10] = 10,}for k , v in ipairs(tblTest) do    print(k,v)end--=============================1    this 12    this 33    24    55    7--=============================local tblTest ={    "this 1",    [3] = 2,    [4] = 5,    [5] = 7,    "this 3",    "this 4",    --"adsfasd",    [10] = 10,}for k , v in ipairs(tblTest) do    print(k,v)end--=============================1    this 12    this 33    this 44    55    7--=============================

It can be seen that the default values in the following table of Lua will be covered, even if the order is adjusted again. As for why, I don't understand it. I need to be enlightened [Please kindly correct ];

There are many such accidents in Lua. It is not surprising that you understand the basic principles;

As for the Lua table traversal can see the http://rangercyh.blog.51cto.com/1444712/1032925 this article; very detailed;

Other minor issues about Lua table:

1. Configure "," or "between the Lua table elements." It is exactly the same. For more information, see the Lua manual. We recommend that you: the split can be separated and displayed as different element types;

2,Do not use the nil value in the Lua table. If an element is to be deleted, remove it directly. Do not use nil instead.

3. Determine whether Lua table is nil. If a = {} Then [incorrect] cannot be used (the result is that a ={} always returns false, which is a logical error. Because the memory address of table A and an anonymous table is compared here .);

If table. maxn (A) = 0 then [incorrect], this is not an insurance policy, unless the table key is a number and there is no hash part.

If # (A) = 0 then is also unreliable, unless you can ensure that no one writes this table like this: tab = {nil,1,Nil;} It is true that the # tab print is 0. Can you say that the tab is nil?

You can use Lua's built-in next to determine; if next (A) = 0 then;

4. I have encountered a lot of things in my daily work. Once I want to write it out, I can't think of it anymore. I want to add it later. [not finished yet ...]

 

Table processing and precautions for Lua

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.