util.cache

This library provides an implementation of an ordered key→value data structure, with a limit on the number of keys. When the cache is full and a new key is added, the oldest key/value pair gets removed. Optionally a callback can be triggered when this happens.

Usage

    local cache = require "util.cache";
 
    -- Create a cache with a maximum limit of 3 key/value pairs:
    local mycache = cache.new(3);
 
    -- Add three different key->value pairs
    mycache:set("a", 1);
    mycache:set("b", 2);
    mycache:set("c", 3);
 
    -- The cache is now full
    print(mycache:count()) --> 3
    print(mycache:get("a")) --> 1
 
    -- Overwrite the first key:
    mycache:set("a", "elephant")
    print(mycache:get("a")) --> "elephant"
 
    -- The cache still contains three items. If we add a new key however, it will go over the limit we set:
    mycache:set("d", 4);
 
    -- Because we updated key "a", the oldest key was "b", so it has been removed:
    print(mycache:get("a"), mycache:get("b")) --> "elephant", nil
    print(mycache:count()) --> 3

Reference

new(limit, evict_callback)

Creates and returns a new cache. The 'limit' option is required, and must be a number greater than 0.

If evict_callback is provided, it must be a function that should be called when the cache has automatically removed an item from a full cache. The callback will receive two values: the key and the value that have been removed from the cache.

cache:set(key, value)

Sets the value to be associated with the given key. If the key exists, the current value is overwritten, and the key becomes the newest item in the cache.

If the key did not previously exist (its associated value was nil) then it is created. If the cache is full, the oldest key/value pair in the cache is removed first.

Keys cannot not be nil. If a key's value is set to nil then the key is removed from the cache.

cache:get(key)

Returns the current value associated with the given key. If the key does not exist in the cache, returns nil.

cache:count()

Returns the number of key→value pairs currently stored in the cache.