lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> Sure it is quite common. Just few examples:
> 1: Telephone book. Table contains pairs name = phone_number. I want to
> know how many entries are in the phone book.
> 2: TV channel guide. Table contains pairs TV_station= channel_number.
> I want to know how many channels did I sign up for.
> 3: Term exams grades. Table contains pairs student_name=test_score. I
> want to know how many student took the test.
> ...
> I can go on and on.
> Besides many hash implementations do keep track of how many entries
> are there in order to decide when to grow hash memory allocation. It
> may be simply a matter of exporting such a counter to the API.

The need to know the number of hash entries is common, and can be easily
computed by a table traversal. I think that lhf meant that it is not so common
as to need an specific idiom for it.

If you really need to keep track of the number of hash entries, one solution
is to create a new hash class and assign a suitable __len metamethod. For

-- hash.lua
local newproxy = newproxy
local getmetatable = getmetatable
local next = next

module 'hash'

function new()
  local t={}
  local n=0
  local u=newproxy(true)
  local mt=getmetatable(u)
  mt.__index = function(o,k) return t[k] end
  mt.__newindex = function(o,k,v)
    if t[k]==nil then n=n+1 elseif v==nil then n=n-1 end
  mt.__len = function(o) return n end
  mt.__hash = t
  return u

function pairs(h)
  return next, getmetatable(h).__hash, nil

Lua 5.1  Copyright (C) 1994-2006, PUC-Rio
> require'hash'
> = #h
> h.k1=10
> h.k2='val'
> = #h
> for k,v in hash.pairs(h) do print(k,v) end
k1      10
k2      val
> h.k1=100
> h.k2=nil
> = #h
> for k,v in hash.pairs(h) do print(k,v) end
k1      100


A mathematician is a device for turning coffee into theorems.
        -- P. Erdos 

Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <>