[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Tracking number of pairs in a dictionary
- From: Doug Currie <doug.currie@...>
- Date: Thu, 1 Oct 2009 13:24:49 -0400
On Oct 1, 2009, at 1:01 PM, Duncan Cross wrote:
On Thu, Oct 1, 2009 at 5:09 PM, Jorge <xxopxe@gmail.com> wrote:
On Wed, 2009-09-30 at 23:34 +0200, Michal Kolodziejczyk wrote:
Or you could keep a counter within the table (so you will not
iterate
the table at all).
Or you can use closures
function make_LimitedTable (limit)
local function make_LimitedTable_MT ()
local n = 0
local MT={
add=function(self, key, value)
if not rawget(self, key) then
if n >= limit then
self:removeOne()
end
n = n + 1
end
rawset(self, key, value)
end,
removeOne=function(self)
self[next(self)]=nil
n = n - 1
print('Removed entry')
end,
del=function(self, key)
if rawget(self, key) and n > 0 then
n = n - 1
end
rawset(self, key, nil)
end
}
MT.__index=MT
return MT
end
return setmetatable({},make_LimitedTable_MT())
end
> t = make_LimitedTable(2)
> t:add('a',{})
> t:add('b',{})
> t:add('c',{})
Removed entry
> for k,v in pairs(t) do print(k,v) end
c table: 0x10b370
b table: 0x101b90
e