# Lua method for determining whether a table is empty

Source: Internet
Author: User

This article mainly introduces LUA to determine whether the table is empty (empty table is {}), how to determine whether the table in Lua is empty table, this article tested a number of methods, and finally come up with a better way to judge, the need for friends can refer to the

Conclusion of the method of judgment:

The code is as follows:

a={}

If Next (a) ~=nil then DoSomething end

LUA, which has recently been heavily used in projects, where LUA table is an important data structure in Lua, can be used as an array in C + +, Vector,map.

How can I tell if a table in Lua is an empty table?

At first I did not move my brain, it was written in this way:

The code is as follows:

a={}

If a ==nil then DoSomething end

This method error is obvious, in Lua A is actually a pointer to the structure of the table, so this method is actually a comparison of whether the address is empty, obviously wrong.

After I improved, the code was as follows:

The code is as follows:

a={}

If a=={} then DoSomething end

A closer look at the above improvement, the equivalent of no change, here's a pointer comparison or an anonymous address, is certainly false.

Then I think that the size of the empty table must be 0, then I directly judge the scale of the table is not finished, so I use the # operator, code improvements to:

The code is as follows:

a={}

If #a ==0 then DoSomething end

But here's the problem, #操作符要求table中的项都不为nil, tragedy! Then I thought of the TABLE.MAXN built-in function, so the code continues to change:

The code is as follows:

a={}

If TABLE.MAXN (a) = = 0 Then DoSomething end

It's not easy, the program can run, but check the relevant data, the MAXN function is based on the hash of each item to judge, so write code is also very safe, unless your table is a full number of keys.

Finally, remember the built-in next function used to traverse a table using a generic method, with the following code improvements:

The code is as follows:

a={}

If Next (a) ~=nil then DoSomething end

Related Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD