Lua, a lightweight script language, has been introduced into Redis since version 2.6. Similar to the transactions in Redis mentioned in the recipe Understanding Redis transactions, a Lua script is executed atomically, while more powerful features and programming logic can be implemented in Lua as a server-side script language. In this recipe, we'll see how to write and execute a Lua script in Redis.
You need to finish the installation of the Redis Server as we described in the Downloading and Installing Redis recipe in Chapter 1, Getting Started with Redis.
The steps for using Lua are as follows:
- We'll use a Lua script to update a JSON string object in Redis.
- Open a console and create a Lua script, as follows:
$ mkdir /redis/coding/lua; cd /redis/coding/lua
$ cat updatejson.lua
local id = KEYS[1]
local data = ARGV[1]
local dataSource = cjson.decode(data)
local retJson = redis.call('get', id)
if retJson == false then
retJson = {}
else
retJson ...