0
0
Redisquery~5 mins

EVAL command for Lua execution in Redis

Choose your learning style9 modes available
Introduction
The EVAL command lets you run small Lua scripts inside Redis to do multiple operations at once, making tasks faster and safer.
When you want to update several keys in Redis atomically without interference.
When you need to perform calculations or logic that Redis commands alone can't do.
When you want to reduce network calls by running multiple commands in one script.
When you want to ensure a sequence of commands runs completely or not at all.
Syntax
Redis
EVAL script numkeys key [key ...] arg [arg ...]
script is the Lua code you want to run, given as a string.
numkeys tells Redis how many keys you are passing next, so it knows which arguments are keys.
Examples
This script returns the value of the key 'mykey'.
Redis
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
This script sets 'mykey' to 'newvalue' and then returns the new value.
Redis
EVAL "redis.call('SET', KEYS[1], ARGV[1]); return redis.call('GET', KEYS[1])" 1 mykey newvalue
Sample Program
This script gets the current value of 'counter', adds 5 to it, saves it back, and returns the new value.
Redis
EVAL "local current = redis.call('GET', KEYS[1]); if not current then current = 0 else current = tonumber(current) end; local new = current + tonumber(ARGV[1]); redis.call('SET', KEYS[1], new); return new" 1 counter 5
OutputSuccess
Important Notes
Lua scripts run atomically in Redis, so no other commands run in the middle.
Use KEYS[] to access keys and ARGV[] to access additional arguments inside the Lua script.
Always specify the correct number of keys to avoid errors.
Summary
EVAL runs Lua scripts inside Redis for complex or multiple operations.
It helps make operations atomic and reduces network calls.
You pass keys and arguments separately so Redis knows which are keys.