Lua學習與交流—— pairs 與 ipairs

【本文內容轉自:http://www.cppblog.com/wc250en007/archive/2011/12/16/162203.html

標準庫提供了集中迭代器,包括迭代文件每行的(io.lines),迭代table元素的(pairs),迭代數組元素的(ipairs),迭代字符串中單詞的 

(string.gmatch)等等。LUA手冊中對與pairs,ipairs解釋如下:

ipairs (t)

Returns three values: an iterator function, the table t, and 0, so that the construction

for i,v in ipairs(t) do body end

will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.

 

 

 

 

pairs (t)

Returns three values: the next function, the table t, and nil, so that the construction

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

 

這樣就可以看出  ipairs以及pairs 的不同。

 

pairs可以遍歷表中所有的key,並且除了迭代器本身以及遍歷表本身還可以返回nil;

 

但是ipairs則不能返回nil,只能返回數字0,如果遇到nil則退出。它只能遍歷到表中出現的第一個不是整數的key

 

  1. 下面舉個例子吧!  
  2.    
  3.  eg:  
  4. local tabFiles = {  
  5. [3] = "test2",  
  6. [6] = "test3",  
  7. [4] = "test1"  
  8. }  
  9.    
  10. for k, v in ipairs(tabFiles) do  
  11. print(k, v)  
  12. end  
  13.    
  14.    
  15. 猜測它的輸出結果是什麼呢?  
  16.    
  17. 根據剛纔的分析,它在 ipairs(tabFiles) 遍歷中,當key=1時候value就是nil,所以直接跳出循環不輸出任何值。  
  18.    
  19. >lua -e "io.stdout:setvbuf 'no'" "Test.lua"  
  20. >Exit code: 0  
  21.    
  22. 那麼,如果是  
  23. for k, v in pairs(tabFiles) do  
  24. print(k, v)  
  25. end  
  26. 則會輸出所有 :  
  27. >lua -e "io.stdout:setvbuf 'no'" "Test.lua"   
  28. 3 test2  
  29. 6 test3  
  30. 4 test1  
  31. >Exit code: 0  
  32. 現在改變一下表內容,  
  33. local tabFiles = {  
  34. [1] = "test1",  
  35. [6] = "test2",  
  36. [4] = "test3"  
  37. }  
  38. for k, v in ipairs(tabFiles) do  
  39. print(k, v)  
  40. end  
  41. 現在的輸出結果顯而易見就是key=1時的value值test1  
  42.  >lua -e "io.stdout:setvbuf 'no'" "Test.lua"   
  43. 1 test1  
  44. >Exit code: 0   
  45. --[示例1.]--  
  46. local tt =  
  47. {  
  48.     [1] = "test3",  
  49.     [4] = "test4",  
  50.     [5] = "test5"  
  51. }  
  52.   
  53. for i,v in pairs(tt) do        -- 輸出 "test4" "test3" "test5"  
  54.     print( tt[i] )  
  55. end  
  56.   
  57. for i,v in ipairs(tt) do    -- 輸出 "test3" k=2時斷開  
  58.     print( tt[i] )  
  59. end  
  60.   
  61.   
  62.   
  63.   
  64.   
  65. -- [[示例2.]] --  
  66. tbl = {"alpha""beta", [3] = "uno", ["two"] = "dos"}  
  67.   
  68. for i,v in ipairs(tbl) do    --輸出前三個  
  69.     print( tbl[i] )  
  70. end  
  71.   
  72. for i,v in pairs(tbl) do    --全部輸出  
  73.     print( tbl[i] )  
  74. end  
發佈了11 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章