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, perform the following operations:
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? This is fine. At least the current project's predecessors are encapsulated in this way, but 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
However, there are also precautions for using next. For Loop pairs a table is implemented using next, but in this loop process, new elements cannot be assigned to the table. Otherwise, the result is unknown, however, you can change the existing value in the loop process. In particular, you can delete an element by assigning it to nil.
1 t = { [1] = 'a', [2] = 'b', [3] = 'c', [32] = 'df', [10] = 'm'} 2 START = 5 3 for k, v in pairs(t) do 4 print(k, v) 5 if k < START then 6 t[k + START] = v 7 t[k] = nil 8 end 9 end10 11 print('****************')12 for k, v in pairs(t) do13 print(k, v)14 end
Execution result
Next is described as follows: