如何在Lua脚本中结合Redis实现奇偶判断并维护数值型键值?
Let's walk through this step by step to clear up your confusion and get your script working exactly as the problem requires.
First: What does "maintain the key's value as a numeric type" mean?
Redis stores most values as strings under the hood, but it automatically recognizes numeric strings when you perform numeric operations (like INCR, DECR, or arithmetic with EVAL). The requirement here just means you shouldn't store string labels like "even" or "odd"—instead, you need to store a number (like 0 for even, 1 for odd, or even the original value if that makes sense for your use case) so Redis treats it as a numeric type.
Fixing Your Script
Your current code uses ARGV[1] for both branches, which doesn't account for the parity check. Instead, we need to set a numeric value based on whether myval is even or odd. Here's the corrected version that meets all the requirements:
-- Declare local variable myval and assign 94 (you had this part right!) local myval = 94 -- Check parity and set the Redis key to a numeric value if myval % 2 == 0 then -- For even numbers: set the key to 0 (numeric) redis.call('SET', KEYS[1], 0) else -- For odd numbers: set the key to 1 (numeric) redis.call('SET', KEYS[1], 1) end -- Optional: Return the set value to verify the result return redis.call('GET', KEYS[1])
If you need to store the original myval (while keeping it numeric)
If the problem expects you to save the original value 94 (but ensure it's treated as numeric), you can adjust the script like this (though the parity check still adds value if you need to flag it later):
local myval = 94 if myval % 2 == 0 then -- Even: store the original numeric value redis.call('SET', KEYS[1], myval) else -- Odd: store the original numeric value redis.call('SET', KEYS[1], myval) end -- Verify the value is numeric by returning it return redis.call('GET', KEYS[1])
Testing the Script
To run this in Redis CLI, use the EVAL command. For example, to set a key named number_parity:
EVAL "local myval = 94 if myval % 2 == 0 then redis.call('SET', KEYS[1], 0) else redis.call('SET', KEYS[1], 1) end return redis.call('GET', KEYS[1])" 1 number_parity
This will return "0" (the string representation of the number 0), and you can confirm it's treated as numeric by running INCR number_parity—it will increment to 1, proving Redis recognizes it as a number.
内容的提问来源于stack exchange,提问作者Sam_2207

