문제

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은 0이 될 수 있습니다. 정규 배열의 경우, 1에서 주어진 n에서 nil 값이 아닌 값을 가진 일반적인 배열의 경우, 길이는 정확히 마지막 값의 색인 인 N입니다. 배열에 "구멍"(즉, 다른 비 닐 값 사이의 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는 테이블을 두 개의 분리 된 부분으로 저장합니다 : 해시 부품 및 배열 부품, LEN 연산자는 배열 부품만을 다루는 것입니다. 즉, 숫자 값으로 색인 된 값과 아래에 언급 된 규칙을 사용하므로 계산할 선택이 없습니다. "해시"값은 테이블 위에 반복해야합니다. 한 쌍() 기능.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top