Redict Lua API reference #
Redict includes an embedded Lua 5.1 interpreter. The interpreter runs user-defined ephemeral scripts and functions. Scripts run in a sandboxed context and can only access specific Lua packages. This page describes the packages and APIs available inside the execution’s context.
Sandbox context #
The sandboxed Lua context attempts to prevent accidental misuse and reduce potential threats from the server’s environment.
Scripts should never try to access the Redict server’s underlying host systems. That includes the file system, network, and any other attempt to perform a system call other than those supported by the API.
Scripts should operate solely on data stored in Redict and data provided as arguments to their execution.
Global variables and functions #
The sandboxed Lua execution context blocks the declaration of global variables and functions. The blocking of global variables is in place to ensure that scripts and functions don’t attempt to maintain any runtime context other than the data stored in Redict. In the (somewhat uncommon) use case that a context needs to be maintain between executions, you should store the context in Redict' keyspace.
Redict will return a “Script attempted to create global variable ‘my_global_variable” error when trying to execute the following snippet:
my_global_variable = 'some value'
And similarly for the following global function declaration:
function my_global_function()
-- Do something amazing
end
You’ll also get a similar error when your script attempts to access any global variables that are undefined in the runtime’s context:
-- The following will surely raise an error
return an_undefined_global_variable
Instead, all variable and function definitions are required to be declared as local. To do so, you’ll need to prepend the local keyword to your declarations. For example, the following snippet will be considered perfectly valid by Redict:
local my_local_variable = 'some value'
local function my_local_function()
-- Do something else, but equally amazing
end
Note: the sandbox attempts to prevent the use of globals. Using Lua’s debugging functionality or other approaches such as altering the meta table used for implementing the globals’ protection to circumvent the sandbox isn’t hard. However, it is difficult to circumvent the protection by accident. If the user messes with the Lua global state, the consistency of AOF and replication can’t be guaranteed. In other words, just don’t do it.
Imported Lua modules #
Using imported Lua modules is not supported inside the sandboxed execution context.
The sandboxed execution context prevents the loading modules by disabling Lua’s require
function.
The only libraries that Redict ships with and that you can use in scripts are listed under the Runtime libraries section.
Runtime globals #
While the sandbox prevents users from declaring globals, the execution context is pre-populated with several of these.
The redict singleton #
The redict singleton is an object instance that’s accessible from all scripts. It provides the API to interact with Redict from scripts. Its description follows below.
Note: The redis singleton is an alias for redict for backwards compatiblity with Redis®.
The KEYS global variable #
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: no
Important: to ensure the correct execution of scripts, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as input key arguments. The script should only access keys whose names are given as input arguments. Scripts should never access keys with programmatically-generated names or based on the contents of data structures stored in the database.
The KEYS global variable is available only for ephemeral scripts. It is pre-populated with all key name input arguments.
The ARGV global variable #
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: no
The ARGV global variable is available only in ephemeral scripts. It is pre-populated with all regular input arguments.
redict object #
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
The Redict Lua execution context always provides a singleton instance of an object named redict. The redict instance enables the script to interact with the Redict server that’s running it. Following is the API provided by the redict object instance.
redict.call(command [,arg...])
#
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
The redict.call()
function calls a given Redict command and returns its reply.
Its inputs are the command and arguments, and once called, it executes the command in Redict and returns the reply.
For example, we can call the ECHO
command from a script and return its reply like so:
return redict.call('ECHO', 'Echo, echo... eco... o...')
If and when redict.call()
triggers a runtime exception, the raw exception is raised back to the user as an error, automatically.
Therefore, attempting to execute the following ephemeral script will fail and generate a runtime exception because ECHO
accepts exactly one argument:
redict> EVAL "return redict.call('ECHO', 'Echo,', 'echo... ', 'eco... ', 'o...')" 0
(error) ERR Wrong number of args calling Redict command from script script: b0345693f4b77517a711221050e76d24ae60b7f7, on @user_script:1.
Note that the call can fail due to various reasons, see Execution under low memory conditions and Script flags
To handle Redict runtime errors use redict.pcall()
instead.
redict.pcall(command [,arg...])
#
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
This function enables handling runtime errors raised by the Redict server.
The redict.pcall()
function behaves exactly like redict.call()
, except that it:
- Always returns a reply.
- Never throws a runtime exception, and returns in its stead a
redict.error_reply
in case that a runtime exception is thrown by the server.
The following demonstrates how to use redict.pcall()
to intercept and handle runtime exceptions from within the context of an ephemeral script.
local reply = redict.pcall('ECHO', unpack(ARGV))
if reply['err'] ~= nil then
-- Handle the error sometime, but for now just log it
redict.log(redict.LOG_WARNING, reply['err'])
reply['err'] = 'ERR Something is wrong, but no worries, everything is under control'
end
return reply
Evaluating this script with more than one argument will return:
redict> EVAL "..." 0 hello world
(error) ERR Something is wrong, but no worries, everything is under control
redict.error_reply(x)
#
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
This is a helper function that returns an error reply. The helper accepts a single string argument and returns a Lua table with the err field set to that string.
The outcome of the following code is that error1 and error2 are identical for all intents and purposes:
local text = 'ERR My very special error'
local reply1 = { err = text }
local reply2 = redict.error_reply(text)
Therefore, both forms are valid as means for returning an error reply from scripts:
redict> EVAL "return { err = 'ERR My very special table error' }" 0
(error) ERR My very special table error
redict> EVAL "return redict.error_reply('ERR My very special reply error')" 0
(error) ERR My very special reply error
For returning Redict status replies refer to redict.status_reply()
.
Refer to the Data type conversion for returning other response types.
Note:
By convention, Redict uses the first word of an error string as a unique error code for specific errors or ERR
for general-purpose errors.
Scripts are advised to follow this convention, as shown in the example above, but this is not mandatory.
redict.status_reply(x)
#
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
This is a helper function that returns a simple string reply. “OK” is an example of a standard Redict status reply. The Lua API represents status replies as tables with a single field, ok, set with a simple status string.
The outcome of the following code is that status1 and status2 are identical for all intents and purposes:
local text = 'Frosty'
local status1 = { ok = text }
local status2 = redict.status_reply(text)
Therefore, both forms are valid as means for returning status replies from scripts:
redict> EVAL "return { ok = 'TICK' }" 0
TICK
redict> EVAL "return redict.status_reply('TOCK')" 0
TOCK
For returning Redict error replies refer to redict.error_reply()
.
Refer to the Data type conversion for returning other response types.
redict.sha1hex(x)
#
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
This function returns the SHA1 hexadecimal digest of its single string argument.
You can, for example, obtain the empty string’s SHA1 digest:
redict> EVAL "return redict.sha1hex('')" 0
"da39a3ee5e6b4b0d3255bfef95601890afd80709"
redict.log(level, message)
#
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
This function writes to the Redict server log.
It expects two input arguments: the log level and a message. The message is a string to write to the log file. Log level can be on of these:
redict.LOG_DEBUG
redict.LOG_VERBOSE
redict.LOG_NOTICE
redict.LOG_WARNING
These levels map to the server’s log levels.
The log only records messages equal or greater in level than the server’s loglevel
configuration directive.
The following snippet:
redict.log(redict.LOG_WARNING, 'Something is terribly wrong')
will produce a line similar to the following in your server’s log:
[32343] 22 Mar 15:21:39 # Something is terribly wrong
redict.setresp(x)
#
- Since version: 6.0.0
- Available in scripts: yes
- Available in functions: yes
This function allows the executing script to switch between
Redis Serialization Protocol (RESP)
versions for the replies returned by
redict.call()
and redict.pcall()
.
It expects a single numerical argument as the protocol’s version.
The default protocol version is 2, but it can be switched to version 3.
Here’s an example of switching to RESP3 replies:
redict.setresp(3)
Please refer to the Data type conversion for more information about type conversions.
redict.set_repl(x)
#
- Since version: 3.2.0
- Available in scripts: yes
- Available in functions: no
Note: this feature is only available when script effects replication is employed. Calling it when using verbatim script replication will result in an error. As of Redict version 2.6.0, scripts were replicated verbatim, meaning that the scripts’ source code was sent for execution by replicas and stored in the AOF. An alternative replication mode added in version 3.2.0 allows replicating only the scripts’ effects. As of Redict version 7.0, script replication is no longer supported, and the only replication mode available is script effects replication.
Warning: this is an advanced feature. Misuse can cause damage by violating the contract that binds the Redict master, its replicas, and AOF contents to hold the same logical content.
This function allows a script to assert control over how its effects are propagated to replicas and the AOF afterward. A script’s effects are the Redict write commands that it calls.
By default, all write commands that a script executes are replicated. Sometimes, however, better control over this behavior can be helpful. This can be the case, for example, when storing intermediate values in the master alone.
Consider a script that intersects two sets and stores the result in a temporary key with SUNIONSTORE
.
It then picks five random elements (SRANDMEMBER
) from the intersection and stores (SADD
) them in another set.
Finally, before returning, it deletes the temporary key that stores the intersection of the two source sets.
In this case, only the new set with its five randomly-chosen elements needs to be replicated.
Replicating the SUNIONSTORE
command and the DEL
ition of the temporary key is unnecessary and wasteful.
The redict.set_repl()
function instructs the server how to treat subsequent write commands in terms of replication.
It accepts a single input argument that only be one of the following:
redict.REPL_ALL
: replicates the effects to the AOF and replicas.redict.REPL_AOF
: replicates the effects to the AOF alone.redict.REPL_REPLICA
: replicates the effects to the replicas alone.redict.REPL_SLAVE
: same asREPL_REPLICA
, maintained for backward compatibility.redict.REPL_NONE
: disables effect replication entirely.
By default, the scripting engine is initialized to the redict.REPL_ALL
setting when a script begins its execution.
You can call the redict.set_repl()
function at any time during the script’s execution to switch between the different replication modes.
A simple example follows:
redict.call('SET', KEYS[1], ARGV[1])
redict.set_repl(redict.REPL_NONE)
redict.call('SET', KEYS[2], ARGV[2])
redict.set_repl(redict.REPL_ALL)
redict.call('SET', KEYS[3], ARGV[3])
If you run this script by calling EVAL "..." 3 A B C 1 2 3
, the result will be that only the keys A and C are created on the replicas and AOF.
redict.breakpoint()
#
- Since version: 3.2.0
- Available in scripts: yes
- Available in functions: no
This function triggers a breakpoint when using the Redict Lua debugger.
redict.debug(x)
#
- Since version: 3.2.0
- Available in scripts: yes
- Available in functions: no
This function prints its argument in the Redict Lua debugger console.
redict.acl_check_cmd(command [,arg...])
#
- Since version: 7.0.0
- Available in scripts: yes
- Available in functions: yes
This function is used for checking if the current user running the script has ACL permissions to execute the given command with the given arguments.
The return value is a boolean true
in case the current user has permissions to execute the command (via a call to redict.call or redict.pcall) or false
in case they don’t.
The function will raise an error if the passed command or its arguments are invalid.
redict.register_function
#
- Since version: 7.0.0
- Available in scripts: no
- Available in functions: yes
This function is only available from the context of the FUNCTION LOAD
command.
When called, it registers a function to the loaded library.
The function can be called either with positional or named arguments.
positional arguments: redict.register_function(name, callback)
#
The first argument to redict.register_function
is a Lua string representing the function name.
The second argument to redict.register_function
is a Lua function.
Usage example:
redict> FUNCTION LOAD "#!lua name=mylib\n redict.register_function('noop', function() end)"
Named arguments: redict.register_function{function_name=name, callback=callback, flags={flag1, flag2, ..}, description=description}
#
The named arguments variant accepts the following arguments:
- function_name: the function’s name.
- callback: the function’s callback.
- flags: an array of strings, each a function flag (optional).
- description: function’s description (optional).
Both function_name and callback are mandatory.
Usage example:
redict> FUNCTION LOAD "#!lua name=mylib\n redict.register_function{function_name='noop', callback=function() end, flags={ 'no-writes' }, description='Does nothing'}"
Script flags #
Important: Use script flags with care, which may negatively impact if misused. Note that the default for Eval scripts are different than the default for functions that are mentioned below, see Eval Flags
When you register a function or load an Eval script, the server does not know how it accesses the database. By default, Redict assumes that all scripts read and write data. This results in the following behavior:
- They can read and write data.
- They can run in cluster mode, and are not able to run commands accessing keys of different hash slots.
- Execution against a stale replica is denied to avoid inconsistent reads.
- Execution under low memory is denied to avoid exceeding the configured threshold.
You can use the following flags and instruct the server to treat the scripts’ execution differently:
-
no-writes
: this flag indicates that the script only reads data but never writes.By default, Redict will deny the execution of flagged scripts (Functions and Eval scripts with shebang) against read-only replicas, as they may attempt to perform writes. Similarly, the server will not allow calling scripts with
FCALL_RO
/EVAL_RO
. Lastly, when data persistence is at risk due to a disk error, execution is blocked as well.Using this flag allows executing the script:
- With
FCALL_RO
/EVAL_RO
- On read-only replicas.
- Even if there’s a disk error (Redict is unable to persist so it rejects writes).
- When over the memory limit since it implies the script doesn’t increase memory consumption (see
allow-oom
below)
However, note that the server will return an error if the script attempts to call a write command. Also note that currently
PUBLISH
,SPUBLISH
andPFCOUNT
are also considered write commands in scripts, because they could attempt to propagate commands to replicas and AOF file.For more information please refer to Read-only scripts
- With
-
allow-oom
: use this flag to allow a script to execute when the server is out of memory (OOM).Unless used, Redict will deny the execution of flagged scripts (Functions and Eval scripts with shebang) when in an OOM state. Furthermore, when you use this flag, the script can call any Redict command, including commands that aren’t usually allowed in this state. Specifying
no-writes
or usingFCALL_RO
/EVAL_RO
also implies the script can run in OOM state (without specifyingallow-oom
) -
allow-stale
: a flag that enables running the flagged scripts (Functions and Eval scripts with shebang) against a stale replica when thereplica-serve-stale-data
config is set tono
.Redict can be set to prevent data consistency problems from using old data by having stale replicas return a runtime error. For scripts that do not access the data, this flag can be set to allow stale Redict replicas to run the script. Note however that the script will still be unable to execute any command that accesses stale data.
-
no-cluster
: the flag causes the script to return an error in Redict cluster mode.Redict allows scripts to be executed both in standalone and cluster modes. Setting this flag prevents executing the script against nodes in the cluster.
-
allow-cross-slot-keys
: The flag that allows a script to access keys from multiple slots.Redict typically prevents any single command from accessing keys that hash to multiple slots. This flag allows scripts to break this rule and access keys within the script that access multiple slots. Declared keys to the script are still always required to hash to a single slot. Accessing keys from multiple slots is discouraged as applications should be designed to only access keys from a single slot at a time, allowing slots to move between Redict servers.
This flag has no effect when cluster mode is disabled.
Please refer to Function Flags and Eval Flags for a detailed example.
redict.REDICT_VERSION
#
- Since version: 7.0.0
- Available in scripts: yes
- Available in functions: yes
Returns the current Redict server version as a Lua string.
The reply’s format is MM.mm.PP
, where:
- MM: is the major version.
- mm: is the minor version.
- PP: is the patch level.
redict.REDICT_VERSION_NUM
#
- Since version: 7.0.0
- Available in scripts: yes
- Available in functions: yes
Returns the current Redict server version as a number.
The reply is a hexadecimal value structured as 0x00MMmmPP
, where:
- MM: is the major version.
- mm: is the minor version.
- PP: is the patch level.
Data type conversion #
Unless a runtime exception is raised, redict.call()
and redict.pcall()
return the reply from the executed command to the Lua script.
Redict’ replies from these functions are converted automatically into Lua’s native data types.
Similarly, when a Lua script returns a reply with the return
keyword,
that reply is automatically converted to Redict’ protocol.
Put differently; there’s a one-to-one mapping between Redict’ replies and Lua’s data types and a one-to-one mapping between Lua’s data types and the Redis Protocol data types. The underlying design is such that if a Redict type is converted into a Lua type and converted back into a Redict type, the result is the same as the initial value.
Type conversion from Re protocol replies (i.e., the replies from redict.call()
and redict.pcall()
) to Lua data types depends on the Redis Serialization Protocol version used by the script.
The default protocol version during script executions is RESP2.
The script may switch the replies’ protocol versions by calling the redict.setresp()
function.
Type conversion from a script’s returned Lua data type depends on the user’s choice of protocol (see the HELLO
command).
The following sections describe the type conversion rules between Lua and Redict per the protocol’s version.
RESP2 to Lua type conversion #
Check the RESP2 reference for details.
The following type conversion rules apply to the execution’s context by default as well as after calling redict.setresp(2)
:
- integer reply -> Lua number
- bulk string reply -> Lua string
- array reply -> Lua table (may have other Redict data types nested)
- status reply -> Lua table with a single ok field containing the status string
- error reply -> Lua table with a single err field containing the error string
- null bulk reply and null multi bulk reply -> Lua false boolean type
Lua to RESP2 type conversion #
Check the RESP2 reference for details.
The following type conversion rules apply by default as well as after the user had called HELLO 2
:
- Lua number -> integer reply (the number is converted into an integer)
- Lua string -> bulk string reply
- Lua table (indexed, non-associative array) -> array reply (truncated at the first Lua
nil
value encountered in the table, if any) - Lua table with a single ok field -> status reply
- Lua table with a single err field -> error reply
- Lua boolean false -> null bulk reply
There is an additional Lua-to-Redict conversion rule that has no corresponding Redict-to-Lua conversion rule:
- Lua Boolean
true
-> integer reply with value of 1.
There are three additional rules to note about converting Lua to Redict data types:
- Lua has a single numerical type, Lua numbers.
There is no distinction between integers and floats.
So we always convert Lua numbers into integer replies, removing the decimal part of the number, if any.
If you want to return a Lua float, it should be returned as a string,
exactly like Redict itself does (see, for instance, the
ZSCORE
command). - There’s no simple way to have nils inside Lua arrays due
to Lua’s table semantics.
Therefore, when Redict converts a Lua array to RESP, the conversion stops when it encounters a Lua
nil
value. - When a Lua table is an associative array that contains keys and their respective values, the converted Redict reply will not include them.
Lua to RESP2 type conversion examples:
redict> EVAL "return 10" 0
(integer) 10
redict> EVAL "return { 1, 2, { 3, 'Hello World!' } }" 0
1) (integer) 1
2) (integer) 2
3) 1) (integer) 3
1) "Hello World!"
redict> EVAL "return redict.call('get','foo')" 0
"bar"
The last example demonstrates receiving and returning the exact return value of redict.call()
(or redict.pcall()
) in Lua as it would be returned if the command had been called directly.
The following example shows how floats and arrays that cont nils and keys are handled:
redict> EVAL "return { 1, 2, 3.3333, somekey = 'somevalue', 'foo', nil , 'bar' }" 0
1) (integer) 1
2) (integer) 2
3) (integer) 3
4) "foo"
As you can see, the float value of 3.333 gets converted to an integer 3, the somekey key and its value are omitted, and the string “bar” isn’t returned as there is a nil
value that precedes it.
RESP3 to Lua type conversion #
RESP3 is a newer version of the Redis Serialization Protocol. It is available as an opt-in choice.
An executing script may call the redict.setresp
function during its execution and switch the protocol version that’s used for returning replies from Redict’ commands (that can be invoked via redict.call()
or redict.pcall()
).
Once Redict’ replies are in RESP3 protocol, all of the RESP2 to Lua conversion rules apply, with the following additions:
- RESP3 map reply -> Lua table with a single map field containing a Lua table representing the fields and values of the map.
- RESP set reply -> Lua table with a single set field containing a Lua table representing the elements of the set as fields, each with the Lua Boolean value of
true
. - RESP3 null -> Lua
nil
. - RESP3 true reply -> Lua true boolean value.
- RESP3 false reply -> Lua false boolean value.
- RESP3 double reply -> Lua table with a single double field containing a Lua number representing the double value.
- RESP3 big number reply -> Lua table with a single big_number field containing a Lua string representing the big number value.
- Verbatim string reply -> Lua table with a single verbatim_string field containing a Lua table with two fields, string and format, representing the verbatim string and its format, respectively.
Note: Presently, RESP3’s attributes, streamed strings and streamed aggregate data types are not supported by the Redict Lua API.
Lua to RESP3 type conversion #
Regardless of the script’s choice of protocol version set for replies with the [redict.setresp()
function] when it calls redict.call()
or redict.pcall()
, the user may opt-in to using RESP3 (with the HELLO 3
command) for the connection.
Although the default protocol for incoming client connections is RESP2, the script should honor the user’s preference and return adequately-typed RESP3 replies, so the following rules apply on top of those specified in the Lua to RESP2 type conversion section when that is the case.
- Lua Boolean -> RESP3 Boolean reply (note that this is a change compared to the RESP2, in which returning a Boolean Lua
true
returned the number 1 to the Redict client, and returning afalse
used to return anull
. - Lua table with a single map field set to an associative Lua table -> RESP3 map reply.
- Lua table with a single set field set to an associative Lua table -> RESP3 set reply. Values can be set to anything and are discarded anyway.
- Lua table with a single double field to an associative Lua table -> RESP3 double reply.
- Lua nil -> RESP3 null.
However, if the connection is set use the RESP2 protocol, and even if the script replies with RESP3-typed responses, Redict will automatically perform a RESP3 to RESP2 conversion of the reply as is the case for regular commands. That means, for example, that returning the RESP3 map type to a RESP2 connection will result in the reply being converted to a flat RESP2 array that consists of alternating field names and their values, rather than a RESP3 map.
Runtime libraries #
The Redict Lua runtime context always comes with several pre-imported libraries.
The following standard Lua libraries are available to use:
- The String Manipulation (string) library
- The Table Manipulation (table) library
- The Mathematical Functions (math) library
- The Operating System Facilities (os) library
In addition, the following external libraries are loaded and accessible to scripts:
- The struct library
- The cjson library
- The cmsgpack library
- The bitop library
os library #
- Since version: 8.0.0
- Available in scripts: yes
- Available in functions: yes
os provides a set of functions for dealing with date, time, and system commands. More details can be found in the Operating System Facilities. Note that for sandbox security, currently only the following os functions is exposed:
os.clock()
struct library #
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
struct is a library for packing and unpacking C-like structures in Lua. It provides the following functions:
All of struct’s functions expect their first argument to be a format string.
struct formats #
The following are valid format strings for struct’s functions:
>
: big endian<
: little endian![num]
: alignmentx
: paddingb/B
: signed/unsigned byteh/H
: signed/unsigned shortl/L
: signed/unsigned longT
: size_ti/In
: signed/unsigned integer with size n (defaults to the size of int)cn
: sequence of n chars (from/to a string); when packing, n == 0 means the whole string; when unpacking, n == 0 means use the previously read number as the string’s length.s
: zero-terminated stringf
: floatd
: double
struct.pack(x)
#
This function returns a struct-encoded string from values. It accepts a struct format string as its first argument, followed by the values that are to be encoded.
Usage example:
redict> EVAL "return struct.pack('HH', 1, 2)" 0
"\x01\x00\x02\x00"
struct.unpack(x)
#
This function returns the decoded values from a struct. It accepts a struct format string as its first argument, followed by encoded struct’s string.
Usage example:
redict> EVAL "return { struct.unpack('HH', ARGV[1]) }" 0 "\x01\x00\x02\x00"
1) (integer) 1
2) (integer) 2
3) (integer) 5
struct.size(x)
#
This function returns the size, in bytes, of a struct. It accepts a struct format string as its only argument.
Usage example:
redict> EVAL "return struct.size('HH')" 0
(integer) 4
cjson library #
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
The cjson library provides fast JSON encoding and decoding from Lua. It provides these functions.
cjson.encode(x)
#
This function returns a JSON-encoded string for the Lua data type provided as its argument.
Usage example:
redict> EVAL "return cjson.encode({ ['foo'] = 'bar' })" 0
"{\"foo\":\"bar\"}"
cjson.decode(x)
#
This function returns a Lua data type from the JSON-encoded string provided as its argument.
Usage example:
redict> EVAL "return cjson.decode(ARGV[1])['foo']" 0 '{"foo":"bar"}'
"bar"
cmsgpack library #
- Since version: 2.6.0
- Available in scripts: yes
- Available in functions: yes
The cmsgpack library provides fast MessagePack encoding and decoding from Lua. It provides these functions.
cmsgpack.pack(x)
#
This function returns the packed string encoding of the Lua data type it is given as an argument.
Usage example:
redict> EVAL "return cmsgpack.pack({'foo', 'bar', 'baz'})" 0
"\x93\xa3foo\xa3bar\xa3baz"
cmsgpack.unpack(x)
#
This function returns the unpacked values from decoding its input string argument.
Usage example:
redict> EVAL "return cmsgpack.unpack(ARGV[1])" 0 "\x93\xa3foo\xa3bar\xa3baz"
1) "foo"
2) "bar"
3) "baz"
bit library #
- Since version: 2.8.18
- Available in scripts: yes
- Available in functions: yes
The bit library provides bitwise operations on numbers. Its documentation resides at Lua BitOp documentation It provides the following functions.
bit.tobit(x)
#
Normalizes a number to the numeric range for bit operations and returns it.
Usage example:
redict> EVAL 'return bit.tobit(1)' 0
(integer) 1
bit.tohex(x [,n])
#
Converts its first argument to a hex string. The number of hex digits is given by the absolute value of the optional second argument.
Usage example:
redict> EVAL 'return bit.tohex(422342)' 0
"000671c6"
bit.bnot(x)
#
Returns the bitwise not of its argument.
bit.bnot(x)
bit.bor(x1 [,x2...])
, bit.band(x1 [,x2...])
and bit.bxor(x1 [,x2...])
#
Returns either the bitwise or, bitwise and, or bitwise xor of all of its arguments. Note that more than two arguments are allowed.
Usage example:
redict> EVAL 'return bit.bor(1,2,4,8,16,32,64,128)' 0
(integer) 255
bit.lshift(x, n)
, bit.rshift(x, n)
and bit.arshift(x, n)
#
Returns either the bitwise logical left-shift, bitwise logical right-shift, or bitwise arithmetic right-shift of its first argument by the number of bits given by the second argument.
bit.rol(x, n)
and bit.ror(x, n)
#
Returns either the bitwise left rotation, or bitwise right rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side.
bit.bswap(x)
#
Swaps the bytes of its argument and returns it. This can be used to convert little-endian 32-bit numbers to big-endian 32-bit numbers and vice versa.