如何获得一个Lua表中的条目数量?

听起来像一个“让我谷歌为你”的问题,但不知何故,我无法find答案。 Lua #操作符只对整数键的条目进行计数, table.getn也是如此:

 tbl = {} tbl["test"] = 47 tbl[1] = 48 print(#tbl, table.getn(tbl)) -- prints "1 1" count = 0 for _ in pairs(tbl) do count = count + 1 end print(count) -- prints "2" 

如何获得所有参赛作品的数量而不计算它们?

你已经有了问题的解决scheme – 唯一的方法是迭代整个表pairs(..)

 function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end 

另外请注意,“#”运算符的定义比这更复杂一点。 让我来说明一下:

 t = {1,2,3} t[5] = 1 t[9] = 1 

根据手册,3,5和9中的任何一个都是#t有效结果。 唯一可行的方法是使用一个没有nil值的连续部分的数组。

您可以设置一个元表来跟踪条目数量,如果频繁需要这个信息,这可能比迭代更快。

有一种方法,但可能会令人失望:使用一个额外的variables(或表中的一个字段)来存储计数,并在每次插入时增加它。

 count = 0 tbl = {} tbl["test"] = 47 count = count + 1 tbl[1] = 48 count = count + 1 print(count) -- prints "2" 

没有其他办法了,#运算符只能用连续键来处理类似数组的表。

 local function CountedTable(x) assert(type(x) == 'table', 'bad parameter #1: must be table') local new_t = {} local mt = {} -- `all` will represent the number of both local all = 0 for k, v in pairs(x) do all = all + 1 end mt.__newindex = function(t, k, v) if v == nil then if rawget(x, k) ~= nil then all = all - 1 end else if rawget(x, k) == nil then all = all + 1 end end rawset(x, k, v) end mt.__index = function(t, k) if k == 'totalCount' then return all else return rawget(x, k) end end return setmetatable(new_t, mt) end local bar = CountedTable { x = 23, y = 43, z = 334, [true] = true } assert(bar.totalCount == 4) assert(bar.x == 23) bar.x = nil assert(bar.totalCount == 3) bar.x = nil assert(bar.totalCount == 3) bar.x = 24 bar.x = 25 assert(bar.x == 25) assert(bar.totalCount == 4) 

似乎当插入方法添加表的元素时,getn将正确返回。 否则,我们必须计算所有元素

 mytable = {} element1 = {version = 1.1} element2 = {version = 1.2} table.insert(mytable, element1) table.insert(mytable, element2) print(table.getn(mytable)) 

它会正确打印2

我知道获取表格中条目的最简单的方法是用'#'。 #tableName只要它们被编号就获取条目的数量:

 tbl={ [1] [2] [3] [4] [5] } print(#tbl)--prints the highest number in the table: 5 

可悲的是,如果他们没有编号,这是行不通的。