Skip to content

Instantly share code, notes, and snippets.

@shirro
Forked from antirez/gist:950965
Created May 2, 2011 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shirro/951084 to your computer and use it in GitHub Desktop.
Save shirro/951084 to your computer and use it in GitHub Desktop.
# 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