这是Module:Cache的文档页面
This module provides a way of storing data between module invocations. Possible data types are strings, numbers, nil and tables. This is useful for templates that tend to appear multiple times on the same page. Do not use this for modules that only appear a single time per page. It will lead to performance decreases.
Warning[]
Metatables are not preserved. To work around this, this module automatically checks for a __tostring
method and converts the table to a string if possible.
Functions[]
Basic[]
cache.auto[]
cache.auto(func, args, prefix)
The cache.auto function is the simplest way of implementing caching. It wraps the function supplying the value and automatically decides whether to execute the function or use a cached version.
It's parameters are:
- The function for which caching should be applied.
- A table holding the functions arguments.
- An optional prefix for the key under which the output will be stored (useful if multiple functions have the same arguments).
In pseudo-code it would look something like this:
function cache.auto(func, args, prefix)
if prefix_args[1]_args[2].isCached() then
return get_cache(prefix_args[1]_args[2])
else
return set_cache(prefix_args[1]_args[2], func(args))
end
end
Advanced[]
Use these functions if you want to manually implement caching in your module.
cache.set[]
cache.set(args, value, prefix)
Stores content. Logs the stored content and the variable name. Returns the content.
cache.get[]
cache.get(args, prefix)
Retrieves content. Returns the content.
Usage[]
local p = {}
local cache = require('Module:Cache')
function p.example(args)
-- First usage of p._example(); Executes the function and stores the value.
cache.auto(p._example, args, 'example_prefix')
-- Second usage; Uses the cached version.
cache.auto(p._example, args, 'example_prefix')
end
function p._example(args)
return args[1]
end
return p
Tests[]
All tests passed.
Name | Expected | Actual | |
---|---|---|---|
test_auto_boolean | |||
test_auto_number | |||
test_auto_string | |||
test_auto_table | |||
test_get_boolean | |||
test_get_no_set | |||
test_get_number | |||
test_get_string | |||
test_get_table | |||
test_set_boolean | |||
test_set_number | |||
test_set_string | |||
test_set_table |