Delete a Lua table element

Source: Internet
Author: User

There are two ways to delete the table element in Lua:
1. assign a fieldNil
2. UseTable. Remove (table, index)

The following describes two methods:

1 Table. Remove

Let's take a look at the function prototype of this library function:

Table. Remove (table, POS)

@ Table: the table to be deleted.
@ Pos: the position of the table element to be deleted. This parameter is optional. If this parameter is not specified, the default value is the table length, that is, the last element of the table is deleted.

 
 
  1. local t = {10, 20, 30, 40,50, 60}
  2. table.remove(t, 3)
  3. for k,v in pairs (t) do
  4. print("t", k, v)
  5. end

Result:

We can see that 3rd elements 30 cannot be found!
In addition, we can also see that the following 40, 50, and 60 move forward one
Therefore, do not use table. Remove () multiple times in the loop. If you must use it, test it with caution!

2 value: Nil

The following code is used as an experiment environment.

 
 
  1. local t =
  2. {
  3. [10] = 1,
  4. [20] = 2,
  5. [30] = 3,
  6. [40] = 4,
  7. [50] = 5,
  8. [60] = 6
  9. }

If table. Remove () is used, the position of POS is hard to find, because the non-array sorting in Lua is based on the hash value.
It may be convenient to assign a value of nil to a table structure that is hard to find in POS,
Suppose I want to delete T [30],

Only

 
 
  1. t[30] = nil
  2. for k,v in pairs (t) do
  3. print("t", k, v)
  4. end

Result:

We can see that t [30], 3 is not found.

Of course, assigning a value to nil is not only used to delete table elements, but can be used to delete any variable!



From Weizhi note (wiz)

Delete a Lua table element

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.