Skip to content

Instantly share code, notes, and snippets.

@shirro shirro/gist:951084 forked from antirez/gist:950965
Created May 2, 2011

Embed
What would you like to do?
# 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
You can’t perform that action at this time.