Lua 判断表是否为空方法

【1】判断表为空的方法

目前为止,Lua语言中判断table表是否为空有三种方式:

(1)#table,当table为数组时直接返回table表的长度。

(2)当table是字典时,返回table的长度

1 function table.size(t)
2     local s = 0;
3     for k, v in pairs(t) do
4         if v ~= nil then s = s + 1 end
5     end
6     return s;
7 end

(3)next(table),利用next函数进行判断。

 1 local t = {hello = 1, world = 2, lucy = 3}
 2 local k, v
 3 while true do
 4     k, v = next(t, k)
 5     print(k ,v)
 6     if not v then break end
 7 end
 8 
 9 --[[ 执行结果
10 hello    1
11 lucy    3
12 world    2
13 nil    nil
14 ]]
15 
16 local tt = {}
17 
18 function isEmpty(tbl)
19     if next(tbl) ~= nil then
20         print("is not empty.")
21     else
22         print("is empty.")
23     end
24 end
25 
26 print(isEmpty(t))
27 print(isEmpty(tt))
28 
29 --[[ 执行结果
30 is not empty.
31 is empty.
32 ]]

Good Good Study, Day Day Up.

顺序 选择 循环 总结