-
-
Save shirro/951084 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Conditional decrement. | |
# | |
# Decrement the value of a key only if the current value is greater than | |
# a specified value. | |
require 'rubygems' | |
require 'redis' | |
r = Redis.new | |
cond_decr = <<LUA | |
function cond_decr(KEYS,ARGV) | |
local value = tonumber(redis('get',KEYS[1])) | |
if value == nil then return {err="Value at key is not integer"} end | |
if value > tonumber(ARGV[1]) | |
then | |
value = value - 1 | |
redis('set',KEYS[1],value) | |
end | |
return value | |
end | |
LUA | |
r.set(:x,4) | |
r.eval(cond_decr,0) | |
5.times { | |
puts(r.eval('return cond_decr(KEYS,ARGV)',1,:x,0)) | |
} | |
--- OUTPUT --- | |
ruby cond-decr.rb | |
3 | |
2 | |
1 | |
0 | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment