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.

順序 選擇 循環 總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM