Bogdan  Dubyk
Bogdan Dubyk

Reputation: 5564

PHP Redis Lua s script issue

I want to use lua script to make atomic Redis operation using php/reids extension, so my code is:

    $command = "
        local hashes = redis.call('smembers', ARGV[1])
        for  hash in pairs(hashes) do
            local keys = redis.call('hkeys', hash)
            for key in pairs(keys) do
                redis.call('hset', key, 0)
            end
        end

        return 1
    ";
    $result = $this->redisClient->evaluate($command, [self::ALL_HASHES]);

this script should take all availavle hashes from self::ALL_HASHES set, loop through each hash, and set value for each hash key to 0. Script is passing, and $error = $this->redisClient->getLastError(); is null, but values are not 0. What I'm doing wrong? I'm new to Lua, it's my first script.

Upvotes: 0

Views: 706

Answers (1)

for_stack
for_stack

Reputation: 23001

You script has 2 problems. First of all, you should use ipairs to iterate the array, instead of pairs. pairs only iterates the key part of the table, and in this case, it iterates the array index. Second, your HSET command misses the key part. Try the following code:

local hashes = redis.call('smembers', ARGV[1])
for i, hash in ipairs(hashes) do
    local keys = redis.call('hkeys', hash)
    for j, key in ipairs(keys) do
        redis.call('hset', hash, key, 0)
    end
end

return 1

Upvotes: 2

Related Questions