add docs for gears.cache

This commit is contained in:
Seth Barberee 2020-01-03 06:42:39 -06:00
parent b8c83fdf9c
commit b9bb9cbe69
5 changed files with 60 additions and 0 deletions

View File

@ -1,4 +1,16 @@
---------------------------------------------------------------------------
--- Cache object with data that can be garbage-collected.
--
-- Here is an example with a basic cache:
--
--@DOC_text_gears_cache_cache_EXAMPLE@
--
-- The example below demonstrates how the garbage collector will clear the
-- cache:
--
--@DOC_text_gears_cache_another_cache_EXAMPLE@
--
--
-- @author Uli Schlachter
-- @copyright 2015 Uli Schlachter
-- @classmod gears.cache

View File

@ -0,0 +1,21 @@
--DOC_GEN_OUTPUT --DOC_HIDE
local gears = require("gears") --DOC_HIDE
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"))

View File

@ -0,0 +1,6 @@
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

View File

@ -0,0 +1,14 @@
--DOC_GEN_OUTPUT --DOC_HIDE
local cache = require("gears.cache") --DOC_HIDE
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))

View File

@ -0,0 +1,7 @@
new entry created with value 0
0
new entry created with value 1
42
new entry created with value 2
84
0