Skip to content

Instantly share code, notes, and snippets.

@klovadis
Created March 15, 2013 14:59
Show Gist options
  • Star 50 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save klovadis/5170446 to your computer and use it in GitHub Desktop.
Save klovadis/5170446 to your computer and use it in GitHub Desktop.
Two Lua scripts for Redis to turn HGETALL and HMGET into dictionary tables
-- gets all fields from a hash as a dictionary
local hgetall = function (key)
local bulk = redis.call('HGETALL', key)
local result = {}
local nextkey
for i, v in ipairs(bulk) do
if i % 2 == 1 then
nextkey = v
else
result[nextkey] = v
end
end
return result
end
-- gets multiple fields from a hash as a dictionary
local hmget = function (key, ...)
if next(arg) == nil then return {} end
local bulk = redis.call('HMGET', key, unpack(arg))
local result = {}
for i, v in ipairs(bulk) do result[ arg[i] ] = v end
return result
end
-- setup a redis hash
redis.call('HMSET', 'myhash',
'field1', 'value1',
'field2', 'value2',
'field4', 'value4',
'field5', 'value5',
'field3', 'value3');
-- put the redis hash into a dictionary table
local mytable = hgetall('myhash')
local mytable2 = hmget('myhash', 'field4', 'field5')
-- print key -> value for mytable
print('mytable:')
for k, v in pairs(mytable) do
print(' ' .. k .. ' -> ' .. v)
end
-- print key -> value for mytable
print('mytable2:')
for k, v in pairs(mytable2) do
print(' ' .. k .. ' -> ' .. v)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment