Created
February 28, 2013 03:10
-
-
Save physacco/5053870 to your computer and use it in GitHub Desktop.
This gist presents 2 Lua functions for converting hash to array and vice versa. This is a common task in Redis Lua scripting.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- $ lua hash2array.lua | |
-- print a table that contains numbers and strings only | |
local f_log_hash = function(hash, name) | |
if name ~= nil then | |
print(name .. ':') | |
end | |
for k, v in pairs(hash) do | |
print(k, ' => ', v) | |
end | |
print() | |
end | |
-- convert a hash to an array | |
-- e.g. {foo='bar'} -> {'foo', 'bar'} | |
local f_hash_to_array = function(hash) | |
local array, i = {}, 1 | |
for k, v in pairs(hash) do | |
array[i], array[i+1], i = k, v, i+2 | |
end | |
return array | |
end | |
-- convert an array to a hash | |
-- e.g. {'foo', 'bar'} -> {foo='bar'} | |
local f_array_to_hash = function(array) | |
local hash, i = {}, nil | |
for k, v in pairs(array) do | |
if k % 2 == 1 then | |
i = v | |
else | |
hash[i] = v | |
end | |
end | |
return hash | |
end | |
----------------------------------------- | |
hash1 = {ten=10, foo='bar', 'hello'} | |
f_log_hash(hash1, 'hash1') | |
array = f_hash_to_array(hash1) -- {1, 'hello', 'ten', 10, 'foo', 'bar'} | |
f_log_hash(array, 'array') | |
hash2 = f_array_to_hash(array) -- {'hello', ten=10, foo='bar'} | |
f_log_hash(hash2, 'hash2') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment