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

我是不是真的有通过在表中的项目进行迭代来获得密钥的数量?

numItems = 0
for k,v in pairs(myTable) do
    numItems = numItems + 1
end
print(numItems) -- this prints 2
有帮助吗?

解决方案

我尝试同时与操作者#和table.getn()。我想table.getn()会做你想要什么,但事实证明它的返回值相同#,即0看来,字典插入无必要的占位符。

循环的钥匙和计数他们好像得到字典大小的唯一途径。

其他提示

长度运算符:

  

的表T的长度被定义为任何整数索引n,使得T [n]为不是nil和T [N + 1]是零;此外,如果T [1]是零,n可以是零。为规则阵列,具有非零值从1到一个给定的n,其长度正好是n,其最后的值的索引。如果该数组有“洞”(即,无其他非零值之间的值),然后#T可以是任何直接先于零值(指数即,它可考虑任何这样的零值作为所述端阵列的)。

所以只得到长度的方法是迭代的。

除了通过键手动迭代,它是简单的通过元方法自动跟踪它。考虑到你可能不希望跟踪你做的每个表的,你可以编写一个函数,可以让你的任何表格转换成键可数的对象。以下是不完美的,但我认为这将说明这一点:

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

使用这将包括的实例:

-- 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

住工作实例

希望这有助于! :)

的Lua存储表作为两个分离部分组成:一个散列部和阵列的一部分,操作者LEN仅处理该阵列的一部分,这意味着通过一个数字值索引值,以及使用下面所说的规则,这样就不会有任何用于计数选择“散列”值你需要遍历表的对()功能

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top