如何在Lua中获取哈希表中的键数?

如何在Lua中获取哈希表中的键数?,lua,hashtable,Lua,Hashtable,我真的必须遍历表中的项才能得到键的数目吗 myTable = {} myTable["foo"] = 12 myTable["bar"] = "blah" print(#myTable) -- this prints 0 我尝试了#运算符和table.getn()。我原以为table.getn()会执行您想要的操作,但事实证明它返回的值与#相同,即0。词典似乎在必要时插入了nil占位符 循环键并计数似乎是获得字典大小的唯一方法。 表t的长度定义为任意整数索引n,使得t[n]不是nil,t[n+

我真的必须遍历表中的项才能得到键的数目吗

myTable = {}
myTable["foo"] = 12
myTable["bar"] = "blah"
print(#myTable) -- this prints 0

我尝试了#运算符和table.getn()。我原以为table.getn()会执行您想要的操作,但事实证明它返回的值与#相同,即0。词典似乎在必要时插入了nil占位符

循环键并计数似乎是获得字典大小的唯一方法。

表t的长度定义为任意整数索引n,使得t[n]不是nil,t[n+1]是nil;此外,如果t[1]为零,则n可以为零。对于从1到给定n的非零值的正则数组,其长度正好是其最后一个值的索引n。如果数组具有“空穴”(即,在其他非零值之间的零值),那么γt可以是直接在零值之前的任何索引(也就是说,它可以考虑任何这样的零值作为数组的末尾)。p>
所以获取长度的唯一方法是对其进行迭代。

Lua将表存储为两个独立的部分:散列部分和数组部分,len运算符只处理数组部分,这意味着由数值索引的值,再加上使用下面提到的规则,所以您没有任何选择来计算“散列”值,您需要使用pairs()函数迭代表。

除了手动迭代键之外,还可以通过元方法自动跟踪它。考虑到您可能不想跟踪生成的每个表,您可以编写一个函数,允许您将任何表转换为键可数对象。以下内容并不完美,但我认为可以说明这一点:

numItems = 0
for k,v in pairs(myTable) do
    numItems = numItems + 1
end
print(numItems) -- this prints 2
使用该方法的示例包括:

function CountedTable(x)
  assert(type(x) == 'table', 'bad parameter #1: must be table')

  local mt = {}
  -- `keys`  will represent the number of non integral indexes
  -- `indxs` will represent the number of integral indexes
  -- `all`   will represent the number of both 
  local keys, indxs, all = 0, 0, 0

  -- Do an initial count of current assets in table. 
  for k, v in pairs(x) do
    if (type(k) == 'number') and (k == math.floor(k)) then indxs = indxs + 1
    else keys = keys + 1 end

    all = all + 1
  end

  -- By using `__nexindex`, any time a new key is added, it will automatically be
  -- tracked.
  mt.__newindex = function(t, k, v)
    if (type(k) == 'number') and (k == math.floor(k)) then indxs = indxs + 1
    else keys = keys + 1 end

    all = all + 1
    t[k] = v
  end

  -- This allows us to have fields to access these datacounts, but won't count as
  -- actual keys or indexes.
  mt.__index = function(t, k)
    if k == 'keyCount' then return keys 
    elseif k == 'indexCount' then return indxs 
    elseif k == 'totalCount' then return all end
  end

  return setmetatable(x, mt)
end


希望这有帮助!:)

print(table.getn(myTable))打印0。#是table.getn的简写,因此您将得到相同的结果要澄清,#tbl将返回表的长度tblTo以进一步澄清#tbl对条目进行计数,直到找到一个nil键。它仅适用于常规(非稀疏)数组。i、 e.您有tbl[1],tbl[2]等,没有删除或无条目。遗憾的是,
命名空间中没有类似的方法。您无法跟踪键的删除。当然可以。您只需使用
\uuu index
\uu newindex
添加一个间接级别。
-- Note `36.35433` would NOT be counted as an integral index.
local foo = CountedTable { 1, 2, 3, 4, [36.35433] = 36.35433, [54] = 54 }
local bar = CountedTable { x = 23, y = 43, z = 334, [true] = true }
local foobar = CountedTable { 1, 2, 3, x = 'x', [true] = true, [64] = 64 }

print(foo.indexCount)    --> 5
print(bar.keyCount)      --> 4
print(foobar.totalCount) --> 6