Module:Cache/doc

From Dota 2 Wiki
Jump to: navigation, search
Lua logo.svg
This is the documentation page for Module:Cache.
It contains usage information, categories and other content that is not part of the original module page.

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[edit]

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[edit]

Basic[edit]

cache.auto[edit]

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:

  1. The function for which caching should be applied.
  2. A table holding the functions arguments.
  3. 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[edit]

Use these functions if you want to manually implement caching in your module.

cache.set[edit]

cache.set(args, value, prefix)

Stores content. Logs the stored content and the variable name. Returns the content.

cache.get[edit]

cache.get(args, prefix)

Retrieves content. Returns the content.

Usage[edit]

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[edit]

YesY All tests passed.

Name Expected Actual
YesY test_auto_boolean
YesY test_auto_number
YesY test_auto_string
YesY test_auto_table
YesY test_get_boolean
YesY test_get_no_set
YesY test_get_number
YesY test_get_string
YesY test_get_table
YesY test_set_boolean
YesY test_set_number
YesY test_set_string
YesY test_set_table