表函式庫教學

lua-users home
wiki

手冊的第 5.5 節中已說明表函式庫 [1]。有關表的詳細資訊請參閱 TablesTutorial

手冊簡要說明了此函式庫的目的。在此引用:「表函式庫中的大多數函式假設表代表陣列或清單。對於這些函式,當我們討論表的「長度」時,我們指的是長度運算式的結果 [例如 #]。」

table.concat(table [, sep [, i [, j]]])

串接表的元素以形成字串。每個元素都必須能夠轉換成字串。可以指定連結元素間放置的分隔字元。此外,可以在表中指定範圍,從第 i 個元素開始到第 j 個元素結束。

> = table.concat({ 1, 2, "three", 4, "five" })
12three4five
> = table.concat({ 1, 2, "three", 4, "five" }, ", ")
1, 2, three, 4, five
> = table.concat({ 1, 2, "three", 4, "five" }, ", ", 2)
2, three, 4, five
> = table.concat({ 1, 2, "three", 4, "five" }, ", ", 2, 4)
2, three, 4

concat 在包含表的表上會失敗,因為它們無法轉換成字串。有關轉換的詳細資訊,請參閱 StringsTutorial

> = table.concat({ 1,2,{} })
stdin:1: bad argument #1 to `concat' (table contains non-strings)
stack traceback:
        [C]: in function `concat'
        stdin:1: in main chunk
        [C]: ?

table.foreach(table, f)

(注意:此函式在 Lua 5.1 中已棄用,但仍可有用於列印表。您應該改用 pairs() 運算式。與 pairs() 相同,table.foreach() 方法並不會保證按順序傳回索引鍵,與此處範例可能暗示的相反。)

將函式 f套用至傳入表的元素。在每個反覆運算中,函式 f會傳入表中該元素的鍵值成對。

> table.foreach({1,"two",3}, print) -- print the key-value pairs


1       1
2       two
3       3
> table.foreach({1,"two",3,"four"}, function(k,v) print(string.rep(v,k)) end)
1
twotwo
333
fourfourfourfour

如果函式 f傳回 nil 值,反覆運算迴圈即會終止。

> table.foreach({1,"two",3}, function(k,v) print(k,v) return k<2 and nil end)
1       1
2       two

表可以包含混合的鍵值索引值元素。table.foreach() 會顯示表中的所有元素。若僅要顯示索引值元素,請參閱 table.foreachi()。有關這個主題的詳細資訊,請參閱 TablesTutorial

> t = { 1,2,"three"; pi=3.14159, banana="yellow" }
> table.foreach(t, print)
1       1
2       2
3       three
pi      3.14159
banana  yellow

table.foreachi(table, f)

(注意:此函式在 Lua 5.1 中已棄用,但仍可有用於列印表。您應該改用 ipairs() 運算式。與 ipairs() 相同,table.foreachi() 方法會保證按順序傳回索引鍵,並略過非索引鍵。)

將函式 f套用至傳入表的元素。在每個反覆運算中,函式 f會傳入表中該元素的索引值成對。這類似於 table.foreach(),但傳入的是索引值成對,而非鍵值成對。如果函式 f傳回 nil 值,反覆運算迴圈即會終止。

> t = { 1,2,"three"; pi=3.14159, banana="yellow" }
> table.foreachi(t, print)
1       1
2       2
3       three
請注意,範例中僅顯示表的索引元素。有關鍵值索引值成對的詳細資訊,請參閱 TablesTutorial

table.sort(表格 [, 比較函數])

將表格的元素原地排序(即改變表格)。

> t = { 3,2,5,1,4 }
> table.sort(t)
> = table.concat(t, ", ")  -- display sorted values
1, 2, 3, 4, 5

如果表格具有指定大小,則只會排序指定範圍,例如:

> t = { 3,2,5,1,4; n=3 }   -- construct a table with user size of 3
> table.sort(t)            -- sort will be limited by user size
> = table.concat(t, ", ")  -- only specified size is concatenated as well

2, 3, 5

可以提供比較函數自訂元素的排序方式。比較函數必須傳回布林值,說明第一個引數是否應在序列中位於第二個引數之前。預設行為是進行「<」比較。例如,以下程式碼的行為與未提供函數相同:

> t = { 3,2,5,1,4 }
> table.sort(t, function(a,b) return a<b end)
> = table.concat(t, ", ")
1, 2, 3, 4, 5        

可看出,如果我們反轉比較,則序列順序也會反轉。

> table.sort(t, function(a,b) return a>b end)
> = table.concat(t, ", ")
5, 4, 3, 2, 1

table.insert(表格, [位置,] 值)

將給定的值新增到表格中。如果給定位置,則在目前位於該位置的元素之前新增值。

> t = { 1,3,"four" }
> table.insert(t, 2, "two")  -- insert "two" at position before element 2
> = table.concat(t, ", ")
1, two, 3, four

如果未指定位置,則我們會將值追加到表格的結尾。

> table.insert(t, 5)         -- no position given so append to end
> = table.concat(t, ", ")
1, two, 3, four, 5

當將元素新增到表格時,表格大小和元素索引都會更新。

> t = { 1,"two",3 }               -- create a table
> = # t                           -- find current size
3
> table.foreach(t, print)         -- display the table contents
1       1
2       two
3       3
> table.insert(t, 1, "inserted")  -- insert an element at the start
> = table.concat(t, ", ")         -- see what we have
inserted, 1, two, 3
> = # t                          -- find the size
4
> table.foreach(t, print)         -- the indexes have been updated
1       inserted
2       1
3       two
4       3

當未指定位置時,會根據計算的大小將元素新增到表格結尾。表格大小可能是使用者指定的,而且並不反映元素數量,例如:

> t = { 1,"two",3; n=10 }  -- create a table with user size
> table.insert(t, "end")   -- insert with no position inserts at "end"
> table.foreach(t, print)  -- display the table contents
1       1
2       two
3       3
11      end
n       11

table.remove(表格 [, 位置])

從表格移除元素。如果指定位置,則會移除位於該位置的元素。會將其餘的元素依序重新編製索引,並更新表格大小以反映變更。此函數會傳回已移除的元素。例如:

> t = { 1,"two",3,"four" }   -- create a table
> = # t                      -- find the size
4
> table.foreach(t, print)    -- have a look at the elements
1       1
2       two
3       3
4       four
> = table.remove(t,2)        -- remove element number 2 and display it
two
> table.foreach(t, print)    -- display the updated table contents
1       1
2       3
3       four
> = # t                      -- find the size
3

如果未給定位置,則會移除表格中的最後一個元素,這個元素是由表格的大小指定的。例如:

> t = { 1,"two","three" }    
> = # t                     -- find the table size (which is removed)
3
> table.foreach(t, print)   -- display contents
1       1
2       two
3       three
> = table.remove(t)         -- remove the element at position "n"
three
> table.foreach(t, print)   -- display updated contents
1       1
2       two
> = # t                     -- display new size
2

如果表格大小並不反映元素數量,則不會移除任何內容,例如:

> t = {1,2,3}
> table.setn(t,10)          -- set user size
> table.foreach(t, print)   -- display table contents, note size "n" is stored internally
1       1
2       2
3       3
> = # t                     -- find the size
10
> = table.remove(t)         -- remove last element
nil
> = # t                     -- find the updated size
9
> table.foreach(t, print)   -- display elements
1       1
2       2
3       3

注意,table.remove 只能使用數字索引。對於字典,您可以使用 tablevariable["index"] = nil; 來取消設定表格條目。


RecentChanges · 喜好設定
編輯 · 歷程
最後編輯於 2017 年 11 月 13 日 下午 3:31 GMT (diff)