當 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.
