如何获取Lua表中的条目数?

时间:2010-04-24 19:10:42

标签: lua

听起来像是“让我谷歌给你”的问题,但不知怎的,我找不到答案。 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"

如何计算所有条目的数量而不计算它们?

9 个答案:

答案 0 :(得分:108)

您已经在问题中找到解决方案 - 唯一的方法是使用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值的连续部分的数组。

答案 1 :(得分:19)

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

答案 2 :(得分:2)

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

count = 0
tbl = {}

tbl["test"] = 47
count = count + 1

tbl[1] = 48
count = count + 1

print(count)   -- prints "2"

没有别的方法,#运算符只能用于连续键的类似数组的表。

答案 3 :(得分:2)

我知道获取表中条目数的最简单方法是使用“#”。 #tableName只要编号就可以获得条目数:

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

可悲的是,如果它们没有编号,则无效。

答案 4 :(得分:2)

您可以使用penlight library。它具有函数size,该函数给出了表的实际大小。

它实现了我们在Lua编程和丢失时可能需要的许多功能。

这里是使用它的示例。

> tablex = require "pl.tablex"
> a = {}
> a[2] = 2
> a[3] = 3 
> a['blah'] = 24

> #a
0

> tablex.size(a)
3

答案 5 :(得分:1)

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)

答案 6 :(得分:1)

function GetTableLng(tbl)
  local getN = 0
  for n in pairs(tbl) do 
    getN = getN + 1 
  end
  return getN
end

您是对的。没有其他方法可以获取表的长度

答案 7 :(得分:0)

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

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

它会正确打印2

答案 8 :(得分:0)

我偶然发现了该线程,并希望发布另一个选项。我使用的是从块控制器生成的Luad,但是它实际上是通过检查表中的值,然后将要检查的值递增1来工作的。最终,表将用完,并且该索引处的值为Nil。

因此,从返回nil的索引中减去1,这就是表的大小。

我有一个TableSize的全局变量,该变量设置为此计数的结果。

function Check_Table_Size()
  local Count = 1
  local CurrentVal = (CueNames[tonumber(Count)])
  local repeating = true
  print(Count)
  while repeating == true do
    if CurrentVal ~= nil then
      Count = Count + 1
      CurrentVal = CueNames[tonumber(Count)]
     else
      repeating = false
      TableSize = Count - 1
    end
  end
  print(TableSize)
end
相关问题