• Lua 数据类型和 Redis 数据类型之间转换


    当 Lua 通过 call() 或 pcall() 函数执行 Redis 命令的时候,命令的返回值会被转换成 Lua 数据结构。 同样地,当 Lua 脚本在 Redis 内置的解释器里运行时,Lua 脚本的返回值也会被转换成 Redis 协议(protocol),然后由 EVAL 将值返回给客户端。

    数据类型之间的转换遵循这样一个设计原则:如果将一个 Redis 值转换成 Lua 值,之后再将转换所得的 Lua 值转换回 Redis 值,那么这个转换所得的 Redis 值应该和最初时的 Redis 值一样。

    换句话说, Lua 类型和 Redis 类型之间存在着一一对应的转换关系。

    Redis 到 Lua 的转换表。

    • Redis integer reply -> Lua number / Redis 整数转换成 Lua 数字
    • Redis bulk reply -> Lua string / Redis bulk 回复转换成 Lua 字符串
    • Redis multi bulk reply -> Lua table (may have other Redis data types nested) / Redis 多条 bulk 回复转换成 Lua 表,表内可能有其他别的 Redis 数据类型
    • Redis status reply -> Lua table with a single ok field containing the status / Redis 状态回复转换成 Lua 表,表内的 ok 域包含了状态信息
    • Redis error reply -> Lua table with a single err field containing the error / Redis 错误回复转换成 Lua 表,表内的 err 域包含了错误信息
    • Redis Nil bulk reply and Nil multi bulk reply -> Lua false boolean type / Redis 的 Nil 回复和 Nil 多条回复转换成 Lua 的布尔值 false

    Lua 到 Redis 的转换表。

    • Lua number -> Redis integer reply (the number is converted into an integer) / Lua 数字转换成 Redis 整数
    • Lua string -> Redis bulk reply / Lua 字符串转换成 Redis bulk 回复
    • Lua table (array) -> Redis multi bulk reply (truncated to the first nil inside the Lua array if any) / Lua 表(数组)转换成 Redis 多条 bulk 回复
    • Lua table with a single ok field -> Redis status reply / 一个带单个 ok 域的 Lua 表,转换成 Redis 状态回复
    • Lua table with a single err field -> Redis error reply / 一个带单个 err 域的 Lua 表,转换成 Redis 错误回复
    • Lua boolean false -> Redis Nil bulk reply. / Lua 的布尔值 false 转换成 Redis 的 Nil bulk 回复

    从 Lua 转换到 Redis 有一条额外的规则,这条规则没有和它对应的从 Redis 转换到 Lua 的规则:

    • Lua boolean true -> Redis integer reply with value of 1. / Lua 布尔值 true 转换成 Redis 整数回复中的 1

    还有下面两点需要重点注意:

    • lua中整数和浮点数之间没有什么区别。因此,我们始终Lua的数字转换成整数的回复,这样将舍去小数部分。如果你想从Lua返回一个浮点数,你应该将它作为一个字符串(见比如ZSCORE命令)。
    • There is no simple way to have nils inside Lua arrays, this is a result of Lua table semantics, so when Redis converts a Lua array into Redis protocol the conversion is stopped if a nil is encountered.
  • 相关阅读:
    Codeforces Round #568 (Div. 2) D. Extra Element
    Codeforces Round #567 (Div. 2) B. Split a Number
    [dp+博弈]棋盘的必胜策略
    [暴力+前缀和]2019牛客暑期多校训练营(第六场)Upgrading Technology
    [set]Codeforces 830B-Cards Sorting
    [二分]煤气灶
    [STL] Codeforces 69E Subsegments
    剑指offer——判断B树是否是A树的子结构
    在浏览器地址栏输入URL执行后网页显示全过程
    链表反转【图解】
  • 原文地址:https://www.cnblogs.com/yanwei-wang/p/6000691.html
Copyright © 2020-2023  润新知