nrk / redis-lua

A Lua client library for the redis key value storage system.
MIT License
731 stars 239 forks source link

Hash commands #1

Closed ghost closed 14 years ago

ghost commented 14 years ago

For support hash command need another multibulk version:

if #args == 1 and type(args[1]) == 'table' then
    for k, v in pairs(args[1]) do

pls., add multibulk2 and change args[1] to args[2]

nrk commented 14 years ago

There's no need to add a multibulk2 function since dealing with special cases for the passed arguments is not a responsibility of protocol serializers. Besides, this would apply (in different ways) only for HMSET and HMGET of all the hash commands currently supported by Redis 2.0. That said, you can roll your own HMSET and HMGET like this:

redis:add_command('hmset', {
    request = function(client, command, ...)
        local args, arguments = {...}, {}
        table.insert(arguments, args[1])
        for k,v in pairs(args[2]) do
            table.insert(arguments, k)
            table.insert(arguments, v)
        end
        redis.requests.multibulk(client, command, unpack(arguments))
    end,
})

redis:add_command('hmget', {
    request = function(client, command, ...)
        local args, arguments = {...}, {}
        if (#args == 2 and type(args[2]) == 'table') then
            table.insert(arguments, args[1])
            for _,v in ipairs(args[2]) do
              table.insert(arguments, v)
            end
            redis.requests.multibulk(client, command, unpack(arguments))
        else
            redis.requests.multibulk(client, command, ...)
        end
    end,
})

redis:hmset('test', { foo = 'bar', hoge = 'piyo' })
local fields = redis:hmget('test', { 'foo', 'hoge' })
local fields_alternative = redis:hmget('test', 'foo', 'hoge')

See also add_commands.lua in the examples directory. Please note that out-of-the-box support for Redis 2.0 will be provided with the next major release, redis-lua currently supports only Redis 1.2.

PS: unpack(arguments) shouldn't be needed but request.multibulk has a bug when serializing arguments passed as a table. This will be fixed in redis-lua 1.0.1.