Luaのハッシュテーブルでキーの数を取得するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/652957

  •  19-08-2019
  •  | 
  •  

質問

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を返すことになる。辞書は必要に応じてnilプレースホルダーを挿入するようだ。

キーをループしてカウントすることは、辞書のサイズを取得する唯一の方法のようです。

他のヒント

長さ演算子:

  

テーブルtの長さは、t [n]がnilでなく、t [n + 1]がnilであるような任意の整数インデックスnに定義されます。さらに、t [1]がnilの場合、nはゼロになる可能性があります。 1から特定のnまでの非nil値を持つ通常の配列の場合、その長さは正確にそのn(最後の値のインデックス)です。配列に<!> quot; holes <!> quot;がある場合(つまり、他の非nil値の間のnil値)、#tはnil値の直前にあるインデックスのいずれかです(つまり、そのようなnil値を配列の終わりと見なすことができます)。

そのため、長さを取得する唯一の方法はそれを反復することです。

キーを手動で繰り返し処理する以外に、メタメソッドを介してキーを自動的に追跡するのは簡単です。作成するすべてのテーブルを追跡したくない場合は、テーブルをキーカウント可能なオブジェクトに変換できる関数を作成するだけです。以下は完璧ではありませんが、ポイントを説明すると思います:

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はテーブルを2つの個別の部分として保存します:ハッシュ部分と配列部分、len演算子は配列部分のみを処理します。これは、数値でインデックス付けされた値を意味し、さらに下記のルールを使用するため、カウントの選択<!> quot; hash <!> quot; pairs()関数を使用してテーブルを反復処理する必要がある値。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top