Skip to content

Instantly share code, notes, and snippets.

@kosmikko
Last active February 3, 2017 11:42
Show Gist options
  • Save kosmikko/335bebbae2d8ee92e3d36ea22689076e to your computer and use it in GitHub Desktop.
Save kosmikko/335bebbae2d8ee92e3d36ea22689076e to your computer and use it in GitHub Desktop.
Redis script to pop the last element from LIST_KEY that doesn't match SEARCH arg
-- pop the last element from LIST_KEY that doesn't match SEARCH arg
local LIST_KEY = KEYS[1]
local SEARCH = ARGV[1]
-- avoid the expensive LRANGE by peeking the last element
local last = redis.call('LINDEX', LIST_KEY, -1)
if not (string.find(last, SEARCH)) then
redis.call('RPOP', LIST_KEY)
return last
end
-- last element is matching -> need to loop though list
local items = redis.call('LRANGE', LIST_KEY, 0, -1)
for i=#items, 1, -1 do
local value = items[i]
if not (string.find(value, SEARCH)) then
redis.call('LREM', LIST_KEY, -1, value)
return value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment