How to Use EVAL Command in Redis for Lua Scripting
Use the
EVAL command in Redis to run Lua scripts directly on the server by providing the script, the number of keys it will access, and the keys and arguments. This allows you to perform complex, atomic operations in Redis with custom logic.Syntax
The EVAL command syntax is:
EVAL script numkeys key [key ...] arg [arg ...]
Where:
scriptis the Lua code you want to run.numkeysis the number of keys the script will access.key [key ...]are the Redis keys the script will use.arg [arg ...]are additional arguments passed to the script.
redis
EVAL <script> <numkeys> <key1> <key2> ... <arg1> <arg2> ...
Example
This example increments the value of a key by a given amount atomically using a Lua script with EVAL.
redis
127.0.0.1:6379> SET counter 10 OK 127.0.0.1:6379> EVAL "local current = redis.call('GET', KEYS[1]) local new = tonumber(current) + tonumber(ARGV[1]) redis.call('SET', KEYS[1], new) return new" 1 counter 5
Output
15
Common Pitfalls
Common mistakes when using EVAL include:
- Not specifying the correct
numkeys, which causes keys and arguments to be misinterpreted. - Using Redis commands in Lua without
redis.callorredis.pcall. - Passing keys as arguments instead of keys, which breaks the script's access to Redis keys.
Always count keys correctly and use KEYS and ARGV arrays properly inside the Lua script.
redis
Wrong: EVAL "return redis.call('GET', ARGV[1])" 0 mykey Right: EVAL "return redis.call('GET', KEYS[1])" 1 mykey
Quick Reference
| Parameter | Description |
|---|---|
| script | Lua code to execute |
| numkeys | Number of keys the script will access |
| key [key ...] | List of Redis keys used by the script |
| arg [arg ...] | Additional arguments passed to the script |
Key Takeaways
Use EVAL to run Lua scripts atomically on Redis server.
Always specify the correct number of keys with numkeys.
Access keys inside Lua script via KEYS array and arguments via ARGV array.
Use redis.call to execute Redis commands inside Lua.
Check common mistakes like mixing keys and arguments.