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 identifier
value (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 minuteB2Lib.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 retrieve
defaultValue (any, optional): Default value if key not found or expired
Returns: any - The cached value or default value
Example:
has
Checks if a key exists in the cache and is not expired.
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.
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.
Returns: boolean - True if cache was cleared
size
Returns the current number of cached entries.
Returns: number - The number of items currently in cache
getStats
Provides comprehensive cache statistics for monitoring and optimization.
Returns: table - Detailed statistics about cache performance and usage
size (number): Current number of entries
maxSize (number): Maximum capacity
utilization (number): Percentage of capacity used
memoryUsage (number): Estimated memory usage in bytes
totalAccess (number): Total access count across all entries
averageAccess (number): Average access count per entry
hitRate (number): Cache hit rate (if tracking enabled)
cleanup
Removes expired entries from the cache.
Returns: number - The number of entries that were cleaned up
getOrSet
Implements the cache-aside pattern: get from cache or compute and store.
Parameters:
key (string): The cache key
callback (function): Function to compute value if not cached
ttl (number, optional): Time to live in milliseconds
Returns: any - The cached or computed value
Example:
mget
Gets multiple values from cache at once.
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.
Parameters:
data (table): Table of key-value pairs to cache
ttl (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.
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.
Parameters:
key (string): The cache key
ttl (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.
Parameters:
key (string): The cache key
Returns: number - Remaining TTL in milliseconds, -1 if key doesn't exist
namespace
Creates a namespaced cache instance.
Parameters:
name (string): The namespace name
Returns: table - Namespaced cache object with same methods
Example:
Configuration
Configure the cache system in config.lua:
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
-- 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")
B2Lib.Cache.has(key)
B2Lib.Cache.delete(key)
B2Lib.Cache.clear()
B2Lib.Cache.size()
B2Lib.Cache.getStats()
B2Lib.Cache.cleanup()
B2Lib.Cache.getOrSet(key, callback, ttl)
local playerData = B2Lib.Cache.getOrSet("player:123", function()
return loadPlayerFromDatabase(123)
end, 60000)
B2Lib.Cache.mget(keys)
B2Lib.Cache.mset(data, ttl)
B2Lib.Cache.keys(pattern)
B2Lib.Cache.expire(key, ttl)
B2Lib.Cache.ttl(key)
B2Lib.Cache.namespace(name)
local playerCache = B2Lib.Cache.namespace("players")
playerCache.set("123", playerData)
local data = playerCache.get("123")
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
}