表库教程

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(table [, comp])

将表的元素就地排序(即修改表)。

> 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(table, [pos,] value)

将给定值插入到表中。如果指定了位置,则在当前位于该位置的元素之前插入该值。

> 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(table [, pos])

从表中移除一个元素。如果指定了位置,则移除该位置的元素。剩余的元素将被重新索引,并且表的大小将更新以反映此更改。此函数返回被移除的元素。例如:

> 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 · preferences
编辑 · 历史
最后编辑于 2017 年 11 月 13 日 上午 9:31 GMT (差异)