redis-lua is a Lua scripting helper for redis-rs
redis-lua allows to insert Redis Lua scripts in Rust code in safer manner. The key features of redis-lua are:
- Compile-time lint for Redis Lua scripts.
- Capturing Rust variables in Lua scripts.
- Safe argument substitution.
- Safely joining multiple Lua scripts.
redis-lua requires nightly.
Invoke a Lua script
[lua
][] macro allows to create the Lua script. The script object implements [Script
][] trait.
The return value from the script can be converted to any types which implement [redis::FromRedisValue
][].
use lua;
#
Any Lua syntax supported by Redis Lua is usable.
- if-else
# use lua;
#
#
- for-loop
# use lua;
#
#
Error reporting
Errors in Lua scripts (such as undefined variables) are detected at compile time.
# use lua;
#
#
error: in lua: `a` is not defined (undefined_variable)
--> src/lib.rs:80:10
|
10 | return a + 1
| ^
error: aborting due to previous error
Capturing a variable
@
with an identifier allows to capture a Rust variable in the script. It allows to capture any types which implement [serde::Serialize
][].
# use lua;
#
#
Argument substitution
$
with an identifier allows to substitute a variable before actually running the script. Same as @
, any types which implement [serde::Serialize
][] can be substituted.
# use lua;
#
#
The difference from @
is that the same script can be called multiple times with different values.
# use lua;
#
#
The script object is clonable if all the variables it captures are clonable or it captures no variables.
Type conversion
@
and $
allow to pass Rust variables to Lua scripts. Primitive types and strings are converted to
the corresponding primitive types/strings in Lua scripts.
A byte vector such as &[u8]
is converted to a Lua string.
Complicated types such as structs, tuples, maps and non-u8 vectors are converted to Lua tables. The name of struct members become the key of tables.
While a single u8 vector is converted to a Lua string, u8 vectors which appear inside a complicated type
is converted to Lua tables by default. To convert them to Lua strings, use [serde_bytes
][] as follows.
# use Serialize;