[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Weak keyed tables with primitive keys
- From: Duncan Cross <duncan.cross@...>
- Date: Wed, 21 Oct 2009 20:36:01 +0100
On Wed, Oct 21, 2009 at 8:28 PM, Petite Abeille
<petite.abeille@gmail.com> wrote:
>
> On Oct 21, 2009, at 7:25 PM, Wim Couwenberg wrote:
>
>> If you cannot reproduce a
>> certain input, it's pointless to keep the output.
>
> Right.
>
> But to follow up on Mark's example, given a path, io.open():read(), and it's
> result, how would one cache the content of a file?
>
> local cache = setmetatable( {}, { __mode = 'k' } )
>
> local function content( aPath )
> local aContent = cache[ aPath ] or io.open( aPath, 'rb' ):read( '*a' )
>
> cache[ aPath ] = aContent
>
> return aContent
> end
>
> The above seems like a memory leak, as 'cache[ aPath ] = aContent' will hold
> everything forever.
> Thoughts?
>
>
I would put the result into its own table and make the cache
weak-valued, not weak-keyed:
local cache = setmetatable( {}, { __mode = 'v' } )
local function content( aPath )
local fromCache = cache[aPath]
if fromCache then return fromCache.value; end
local aContent = io.open( aPath, 'rb' ):read( '*a' )
cache[ aPath ] = {value=aContent}
return aContent
end
-Duncan