[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Weak keyed tables with primitive keys
- From: Petite Abeille <petite_abeille@...>
- Date: Wed, 21 Oct 2009 22:08:32 +0200
On Oct 21, 2009, at 9:39 PM, Petite Abeille wrote:
On Oct 21, 2009, at 9:36 PM, Duncan Cross wrote:
I would put the result into its own table and make the cache
weak-valued, not weak-keyed:
cache[ aPath ] = {value=aContent}
Right. But then it would get garbage collected right away as nothing
would have any reference to that wrapper table, no?
Something along those lines:
local cache = setmetatable( {}, { __mode = 'v' } )
local function content( aPath )
local aCache = cache[ aPath ]
if not aCache then
print( 'miss', aPath )
aCache = { io.open( aPath, 'rb' ):read( '*a' ) }
cache[ aPath ] = aCache
else
print( 'hit', aPath )
end
return aCache[ 1 ]
end
local aPath = 'TestGC.lua'
content( aPath )
content( aPath )
collectgarbage()
content( aPath )
> miss TestGC.lua
> hit TestGC.lua
> miss TestGC.lua
So the lifespan of the cache would only be the interval between
collectgarbage, instead of the lifespan of the key, as intended
originally.