(Conversion) judgment on whether Lua table is null

Source: Internet
Author: User

This is often the case in the project script Lua,

1. Local A = {}

2. process

3. Determine whether Table A is empty.

To determine whether a is a null table, I found some code to do this:

If a =={} then

The result is that a ={} always returns false, which is a logical error. The memory address of table A and an anonymous table is compared here.

Some codes do the following:

If table. maxn (A) = 0 then

It is not safe to do so unless the table key is a number and there is no hash part.

Do you really need to traverse the table and find that there is something, and return false jumps out to determine whether it is empty? At least the code is too ugly.

I searched the internet and found that the answer was already provided in the original official manual, that is, the next function built in Lua.

That is, if next (A) = nil then

Next is actually a function used by pairs to retrieve the next content when traversing the table.

It is best to encapsulate the module in the project so that the module does not have the next function locally.

Therefore, the function to determine whether the Lua table is empty after encapsulation is as follows:

Function table_is_empty (t)

Return _ g. Next (t) = Nil

End

Original address http://yy1983228.blog.163.com/blog/static/54211491200881092239485/

(Conversion) judgment on whether Lua table is null

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.