0
0
RedisHow-ToBeginner · 3 min read

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:

  • script is the Lua code you want to run.
  • numkeys is 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.call or redis.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

ParameterDescription
scriptLua code to execute
numkeysNumber 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.