Script and ScriptRO classes allow you to execute Lua scripts efficiently by using Redis’s EVALSHA command, which caches scripts on the server for faster execution.
Overview
Scripts provide an optimized way to execute Lua code in Redis:- First execution attempts
EVALSHAwith the script’s SHA-1 hash - If the script isn’t cached, falls back to
EVALto load and execute it - Subsequent executions use the cached version via
EVALSHA
Creating Scripts
Script (Read-Write)
Create a script that can modify data:ScriptRO (Read-Only)
Create a read-only script that usesEVAL_RO and EVALSHA_RO:
string
required
The Lua script to execute
{ readonly?: boolean }
Script configuration options
Script<TResult> | ScriptRO<TResult>
A Script or ScriptRO instance based on the readonly option
Script Class
Properties
script
The Lua script source code.string
The Lua script source code
sha1
The SHA-1 hash of the script.string
The SHA-1 hash of the script (may be empty if not yet initialized)
Methods
eval()
Execute the script using theEVAL command (sends full script to Redis).
string[]
required
Array of Redis keys that the script will access
string[]
required
Array of additional arguments to pass to the script
TResult
The script execution result
evalsha()
Execute the script using theEVALSHA command (uses cached SHA-1 hash).
string[]
required
Array of Redis keys that the script will access
string[]
required
Array of additional arguments to pass to the script
TResult
The script execution result
exec()
Optimistically execute the script with automatic fallback.- First attempts
EVALSHA(fast, uses cached script) - If script not cached (NOSCRIPT error), falls back to
EVAL - Subsequent calls use the cached version
string[]
required
Array of Redis keys that the script will access. In Lua, access via
KEYS[1], KEYS[2], etc.string[]
required
Array of additional arguments. In Lua, access via
ARGV[1], ARGV[2], etc.TResult
The script execution result
ScriptRO Class
TheScriptRO class is identical to Script but uses read-only commands (EVAL_RO and EVALSHA_RO). This is useful for scripts that only read data and can be executed on read replicas.
Methods
evalRo()
Execute the script usingEVAL_RO.
string[]
required
Array of Redis keys to read
string[]
required
Array of additional arguments
TResult
The script execution result
evalshaRo()
Execute the script usingEVALSHA_RO.
string[]
required
Array of Redis keys to read
string[]
required
Array of additional arguments
TResult
The script execution result
exec()
Execute with automatic fallback (triesEVALSHA_RO, falls back to EVAL_RO).
string[]
required
Array of Redis keys to read
string[]
required
Array of additional arguments
TResult
The script execution result