How to Use Lua Script in Redis: Syntax and Examples
You can run Lua scripts in Redis using the
EVAL command, which takes the script, number of keys, and keys/arguments as parameters. Lua scripts run atomically inside Redis, allowing complex operations in a single call.Syntax
The basic syntax to run a Lua script in Redis is:
EVAL <script> <numkeys> <key1> <key2> ... <arg1> <arg2> ...- <script>: The Lua code as a string.
- <numkeys>: Number of keys the script will access.
- <key1>, <key2>, ...: The keys the script will use.
- <arg1>, <arg2>, ...: Additional arguments passed to the script.
This lets Redis know which keys the script will touch and what extra data it needs.
redis
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
Output
"value_of_mykey"
Example
This example shows a Lua script that increments a key's value by a given amount atomically.
redis
EVAL "local current = redis.call('GET', KEYS[1]) if not current then current = 0 else current = tonumber(current) end local increment = tonumber(ARGV[1]) local new = current + increment redis.call('SET', KEYS[1], new) return new" 1 counter 5
Output
5
Common Pitfalls
Common mistakes when using Lua scripts in Redis include:
- Not specifying the correct
numkeyscount, which causes keys and arguments to be misinterpreted. - Using Redis commands incorrectly inside Lua; always use
redis.call()orredis.pcall(). - Assuming Lua scripts can access keys not passed as arguments; Redis restricts scripts to declared keys for safety.
- Not converting string values to numbers before arithmetic operations.
redis
Wrong: EVAL "return redis.call('GET', KEYS[1])" 0 mykey Right: EVAL "return redis.call('GET', KEYS[1])" 1 mykey
Quick Reference
| Parameter | Description |
|---|---|
EVAL | Command to run Lua script in Redis |
<script> | Lua code string to execute |
<numkeys> | Number of keys script will access |
KEYS[1..n] | Keys passed to the script |
ARGV[1..n] | Additional arguments passed to the script |
redis.call() | Call Redis commands inside Lua |
| Atomicity | Scripts run atomically, no other commands run during execution |
Key Takeaways
Use the EVAL command with Lua code, number of keys, keys, and arguments to run scripts in Redis.
Always specify the correct number of keys to avoid errors in key and argument handling.
Use redis.call() inside Lua to execute Redis commands safely and atomically.
Lua scripts in Redis run atomically, ensuring consistent data changes.
Convert string values to numbers in Lua before doing math operations.