lua-users home
lua-l archive

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


Jorge wrote:
[...]
> So i would like to have a way for knowing how many entries are already
> in the dictionary without having to iterate everything.
> 
> The best idea i have is pretty ad-hoc, to lazily count the entries in
> some iteration i already have to perform (i have certain latitude with
> numbers).

Or you could keep a counter within the table (so you will not iterate
the table at all). Here is an example implementation (you can overide
removeOne() to what you need):

MT={
  add=function(self, key, value)
    if not rawget(self, key) then
      if self._n>=self._limit then
        self:removeOne()
      end
      self._n=self._n+1
    end
    rawset(self, key, value)
  end,
  removeOne=function(self)
    self[next(self)]=nil
      self._n=self._n-1
      print('Removed entry')
  end,
  del=function(self, key)
    if rawget(self, key) and self._n>0 then
      self._n=self._n-1
    end
    rawset(self, key, nil)
  end
}
MT.__index=MT

LimitedTable={
  new=function(limit)
    return setmetatable({_n=0, _limit=limit}, MT)
  end,
}

T=LimitedTable.new(2)
T:add('one',{})
T:add('two',{})
T:add('three',{})

Regards,
	miko