lua-users home
lua-l archive

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

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 = { aPath, 'rb' ):read( '*a' ) }
        cache[ aPath ] = aCache
        print( 'hit', aPath )

    return aCache[ 1 ]

local aPath = 'TestGC.lua'

content( aPath )
content( aPath )
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.