Redis is a free, open-source in-memory database widely adopted as a caching mechanism or message broker.
Although it is very versatile and extensive by default, it does allow you to extend functionality using its embedded Lua interpreter. This means that you can write scripts written in Lua to perform additional operations on your Redis database.
To better follow along with this tutorial, we recommended having the latest version of the Redis server on your system.
Basic Redis knowledge is beneficial to understand the commands illustrated in this tutorial.
Redis EVAL Command
To run Lua commands in Redis, you need to use the EVAL command. The command tells Redis to execute the code as a server-side Lua script.
An example is as shown:
In the example above, we start with the EVAL command followed by a Lua script. The script uses the redis.call function. We then pass the command to run, key, and value as the arguments. This is similar to running SET key values.
Note that KEYS and ARGV denote the arguments of the script. We specify the number of keys as 1 in this case.
Argument parsing is done via the ARGV, which holds the argument table. In our case, we pass the value of the key.
We can then access the keys starting from index 1.
NOTE: It is recommended to specify all the keys used in the script under KEYS and all other arguments under ARGV.
We can fetch the value of a key using the get command:
This should return the value of the specified key.
Redis EVALSHA command
Redis also provides you with the EVALSHA command to recall a command based on its hash value.
This removes the need to retype the script every time you need it.
The command above should return a SHA value as:
You can then use this sha value to recall a command.
To remove all loaded scripts, run the command:
The command above should flush the script cache.
This article describes the most basic commands to use when working with LUA scripting in Redis. Check the Lua documentation to discover more.