如何在Redis Lua脚本中正确检查键的类型?
Redis Lua脚本中正确检查键类型的方法
问题核心在于Redis的TYPE命令在Lua脚本中返回的不是字符串,而是一个包含ok和type字段的Lua表(table)。虽然直接返回这个变量时,Redis会自动将其格式化为字符串输出,但在Lua代码内部做比较时,必须访问表中的type字段才能拿到真正的类型字符串。
错误原因分析
你之前的尝试里,直接把type变量(实际是表结构)和字符串"string"或Lua的string类型做比较,自然无法匹配,所以一直返回"not ok"。
正确写法示例
127.0.0.1:6379> EVAL 'local type_info = redis.call("TYPE", KEYS[1]); local res; if type_info.type == "string" then res = "ok" else res = "not ok" end return res' 1 test_key "ok"
也可以简化成一行写法:
127.0.0.1:6379> EVAL 'return redis.call("TYPE", KEYS[1]).type == "string" and "ok" or "not ok"' 1 test_key "ok"
查看返回的完整结构
你可以通过以下脚本确认TYPE命令返回的表结构细节:
127.0.0.1:6379> EVAL 'local type_info = redis.call("TYPE", KEYS[1]); return cjson.encode(type_info)' 1 test_key "{\"ok\":\"string\",\"type\":\"string\"}"
内容的提问来源于stack exchange,提问作者Michael Kosh
相关产品推荐
相关产品推荐

