Module: gears.cache
Cache object with data that can be garbage-collected.
Here is an example with a basic cache:
Usage example output:
new entry created with value 0 0 new entry created with value 1 42 new entry created with value 2 84 0
Usage:
local test_cache = cache.new(function(test) -- let's just print about what we created print("new entry created with value " .. test) -- Pretend this is some expensive computation return test * 42 end) -- Populate the cache print(test_cache:get(0)) print(test_cache:get(1)) print(test_cache:get(2)) -- no message since it exists print(test_cache:get(0)) The example below demonstrates how the garbage collector will clear the cache: *Usage example output**: cache object #0 for first cache object #1 for second cache object #0 for first forcing a garbage collect cache object #2 for first cache object #3 for second
local function tostring_for_cache(obj) return obj[1] end local counter = 0 local wrapper_cache = gears.cache.new(function(arg) local kind = "cache object #" .. tostring(counter) .. " for " .. tostring(arg) counter = counter + 1 return setmetatable({ kind }, { __tostring = tostring_for_cache }) end) print(wrapper_cache:get("first")) print(wrapper_cache:get("second")) -- No new object since it already exists print(wrapper_cache:get("first")) print("forcing a garbage collect") -- The GC can *always* clear the cache collectgarbage("collect") print(wrapper_cache:get("first")) print(wrapper_cache:get("second"))
Info:
- Copyright: 2015 Uli Schlachter
-
Originally authored by: Uli Schlachter
(Full contributors list available on our github project)
Constructors
gears.cache (creation_cb) | Create a new cache object. |
Methods
:get (...) | Get an entry from the cache, creating it if it's missing. |
Constructors
- gears.cache (creation_cb)
-
Create a new cache object. A cache keeps some data that can be
garbage-collected at any time, but might be useful to keep.
Parameters:
- creation_cb Callback that is used for creating missing cache entries.
Returns:
-
A new cache object.