github.com/awirix/lua@v1.6.0/_lua5.1-tests/checktable.lua (about)

     1  
     2  assert(rawget(_G, "stat") == nil)  -- module not loaded before
     3  
     4  if T == nil then
     5    stat = function () print"`querytab' nao ativo" end
     6    return
     7  end
     8  
     9  
    10  function checktable (t)
    11    local asize, hsize, ff = T.querytab(t)
    12    local l = {}
    13    for i=0,hsize-1 do
    14      local key,val,next = T.querytab(t, i + asize)
    15      if key == nil then
    16        assert(l[i] == nil and val==nil and next==nil)
    17      elseif key == "<undef>" then
    18        assert(val==nil)
    19      else
    20        assert(t[key] == val)
    21        local mp = T.hash(key, t)
    22        if l[i] then
    23          assert(l[i] == mp)
    24        elseif mp ~= i then
    25          l[i] = mp
    26        else  -- list head
    27          l[mp] = {mp}   -- first element
    28          while next do
    29            assert(ff <= next and next < hsize)
    30            if l[next] then assert(l[next] == mp) else l[next] = mp end
    31            table.insert(l[mp], next)
    32            key,val,next = T.querytab(t, next)
    33            assert(key)
    34          end
    35        end
    36      end
    37    end
    38    l.asize = asize; l.hsize = hsize; l.ff = ff
    39    return l
    40  end
    41  
    42  function mostra (t)
    43    local asize, hsize, ff = T.querytab(t)
    44    print(asize, hsize, ff)
    45    print'------'
    46    for i=0,asize-1 do
    47      local _, v = T.querytab(t, i)
    48      print(string.format("[%d] -", i), v)
    49    end
    50    print'------'
    51    for i=0,hsize-1 do
    52      print(i, T.querytab(t, i+asize))
    53    end
    54    print'-------------'
    55  end
    56  
    57  function stat (t)
    58    t = checktable(t)
    59    local nelem, nlist = 0, 0
    60    local maxlist = {}
    61    for i=0,t.hsize-1 do
    62      if type(t[i]) == 'table' then
    63        local n = table.getn(t[i])
    64        nlist = nlist+1
    65        nelem = nelem + n
    66        if not maxlist[n] then maxlist[n] = 0 end
    67        maxlist[n] = maxlist[n]+1
    68      end
    69    end
    70    print(string.format("hsize=%d  elements=%d  load=%.2f  med.len=%.2f (asize=%d)",
    71            t.hsize, nelem, nelem/t.hsize, nelem/nlist, t.asize))
    72    for i=1,table.getn(maxlist) do
    73      local n = maxlist[i] or 0
    74      print(string.format("%5d %10d %.2f%%", i, n, n*100/nlist))
    75    end
    76  end
    77