SHARE
TWEET

Untitled

a guest Feb 17th, 2017 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- gets all fields from a hash as a dictionary
  2. local hgetall = function (key)
  3.   local bulk = redis.call('HGETALL', key)
  4.     local result = {}
  5.     local nextkey
  6.     for i, v in ipairs(bulk) do
  7.         if i % 2 == 1 then
  8.             nextkey = v
  9.         else
  10.             result[nextkey] = v
  11.         end
  12.     end
  13.     return result
  14. end
  15.  
  16. -- gets multiple fields from a hash as a dictionary
  17. local hmget = function (key, ...)
  18.     if next(arg) == nil then return {} end
  19.     local bulk = redis.call('HMGET', key, unpack(arg))
  20.     local result = {}
  21.     for i, v in ipairs(bulk) do result[ arg[i] ] = v end
  22.     return result
  23. end
  24.  
  25.  
  26. -- setup a redis hash
  27. redis.call('HMSET', 'myhash',
  28.     'field1', 'value1',
  29.     'field2', 'value2',
  30.     'field4', 'value4',
  31.     'field5', 'value5',
  32.     'field3', 'value3');
  33.  
  34. -- put the redis hash into a dictionary table
  35. local mytable = hgetall('myhash')
  36. local mytable2 = hmget('myhash', 'field4', 'field5')
  37.  
  38.  
  39. -- print key -> value for mytable
  40. print('mytable:')
  41. for k, v in pairs(mytable) do
  42.     print('    ' .. k .. ' -> ' .. v)
  43. end
  44.  
  45. -- print key -> value for mytable
  46. print('mytable2:')
  47. for k, v in pairs(mytable2) do
  48.     print('    ' .. k .. ' -> ' .. v)
  49. end
RAW Paste Data
Top