[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Tracking number of pairs in a dictionary
- From: Michal Kolodziejczyk <miko@...>
- Date: Wed, 30 Sep 2009 23:34:46 +0200
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