Cache
The Cache module provides a comprehensive caching system for FiveM resources with advanced features including TTL (Time To Live), automatic cleanup, LRU eviction, and namespace support.
set
Stores a value in the cache with optional TTL.
B2Lib.Cache.set(key, value, ttl)
Parameters:
key
(string): The unique cache key identifiervalue
(any): The value to store (any Lua type)ttl
(number, optional): Time to live in milliseconds (default: 300000)
Returns: boolean - True if successfully cached, false otherwise
Example:
-- Cache player data for 1 minute
B2Lib.Cache.set("player:123", playerData, 60000)
-- Cache with default TTL (5 minutes)
B2Lib.Cache.set("config:server", serverConfig)
get
Retrieves a value from the cache.
B2Lib.Cache.get(key, defaultValue)
Parameters:
key
(string): The cache key to retrievedefaultValue
(any, optional): Default value if key not found or expired
Returns: any - The cached value or default value
Example:
-- Get cached player data or empty table
local playerData = B2Lib.Cache.get("player:123", {})
-- Get cached value with nil default
local config = B2Lib.Cache.get("app:config")
has
Checks if a key exists in the cache and is not expired.
B2Lib.Cache.has(key)
Parameters:
key
(string): The cache key to check
Returns: boolean - True if key exists and is valid, false otherwise
delete
Removes a specific entry from the cache.
B2Lib.Cache.delete(key)
Parameters:
key
(string): The cache key to delete
Returns: boolean - True if successfully deleted, false if key didn't exist
clear
Clears all entries from the cache.
B2Lib.Cache.clear()
Returns: boolean - True if cache was cleared
size
Returns the current number of cached entries.
B2Lib.Cache.size()
Returns: number - The number of items currently in cache
getStats
Provides comprehensive cache statistics for monitoring and optimization.
B2Lib.Cache.getStats()
Returns: table - Detailed statistics about cache performance and usage
size
(number): Current number of entriesmaxSize
(number): Maximum capacityutilization
(number): Percentage of capacity usedmemoryUsage
(number): Estimated memory usage in bytestotalAccess
(number): Total access count across all entriesaverageAccess
(number): Average access count per entryhitRate
(number): Cache hit rate (if tracking enabled)
cleanup
Removes expired entries from the cache.
B2Lib.Cache.cleanup()
Returns: number - The number of entries that were cleaned up
getOrSet
Implements the cache-aside pattern: get from cache or compute and store.
B2Lib.Cache.getOrSet(key, callback, ttl)
Parameters:
key
(string): The cache keycallback
(function): Function to compute value if not cachedttl
(number, optional): Time to live in milliseconds
Returns: any - The cached or computed value
Example:
local playerData = B2Lib.Cache.getOrSet("player:123", function()
return loadPlayerFromDatabase(123)
end, 60000)
mget
Gets multiple values from cache at once.
B2Lib.Cache.mget(keys)
Parameters:
keys
(table): Array of cache keys to retrieve
Returns: table - Table with keys and their cached values
mset
Sets multiple key-value pairs in cache at once.
B2Lib.Cache.mset(data, ttl)
Parameters:
data
(table): Table of key-value pairs to cachettl
(number, optional): Time to live in milliseconds
Returns: boolean - True if all values were cached successfully
keys
Gets all cache keys, optionally filtered by pattern.
B2Lib.Cache.keys(pattern)
Parameters:
pattern
(string, optional): Lua pattern to filter keys
Returns: table - Array of matching cache keys
expire
Sets or updates the TTL for an existing cache entry.
B2Lib.Cache.expire(key, ttl)
Parameters:
key
(string): The cache keyttl
(number): New time to live in milliseconds
Returns: boolean - True if TTL was updated, false if key doesn't exist
ttl
Gets the remaining time to live for a cache entry.
B2Lib.Cache.ttl(key)
Parameters:
key
(string): The cache key
Returns: number - Remaining TTL in milliseconds, -1 if key doesn't exist
namespace
Creates a namespaced cache instance.
B2Lib.Cache.namespace(name)
Parameters:
name
(string): The namespace name
Returns: table - Namespaced cache object with same methods
Example:
local playerCache = B2Lib.Cache.namespace("players")
playerCache.set("123", playerData)
local data = playerCache.get("123")
Configuration
Configure the cache system in config.lua
:
Config.Cache = {
maxSize = 1000, -- Maximum number of cached entries
defaultTTL = 300000, -- Default TTL: 5 minutes
cleanupInterval = 60000, -- Cleanup every 1 minute
evictionPolicy = 'lru', -- Least Recently Used eviction
enableStats = true, -- Enable hit rate tracking
debugMode = false -- Enable debug logging
}
Troubleshooting
Values Not Being Cached
Check that the key is a valid string
Verify TTL is not too short
Ensure cache hasn't reached maxSize limit
Check console for error messages
High Memory Usage
Reduce maxSize in configuration
Use shorter TTL values for temporary data
Call cleanup() manually if needed
Monitor cache stats with getStats()
Poor Performance
Use batch operations (mget/mset) for multiple keys
Implement proper TTL values to avoid unnecessary storage
Use namespaces to organize cache data
Monitor hit rate and adjust caching strategy
Cache Misses
Verify keys are consistent (case-sensitive)
Check if TTL is appropriate for data lifetime
Use getOrSet() pattern for automatic cache population
Monitor cache statistics to identify patterns
Last updated