user647527
user647527

Reputation: 319

Redis-Lua array key in string

I execute Lua under Redis. I face an issue which is that I can't use a string as an array key. My coding is like following, and we found that mytable["wow"] is discarded:

FileName: hget.lua

local mytable = {}
mytable[1]= "Lua"
mytable["wow"] = "Tutorial"
return mytable

Command:redis-cli --eval hget.lua   

Result returned is:

1) "Lua"

Upvotes: 1

Views: 1175

Answers (1)

for_stack
for_stack

Reputation: 23021

You CANNOT have a string key for the table, if you want to return the table to Redis.

Redis takes the returned table as an array, whose index starting from 1. It discards other elements of the table whose keys are NOT integers. In your case, i.e. mytable["wow"] = "Tutorial", since the key is a string, Redis ignores this element.

Also, the indexes must be sequential, otherwise, Redis discards some elements. Take the following as an example:

local t = {}
t[1] = "1"    -- OK
t[2] = "2"    -- OK
t[4] = "4"    -- since index 3 is missing, this element will be discarded
t["string_key"] = "value"   -- since the key is string, this element will be discarded

return t

Result:

./redis-cli --eval t.lua 
1) "1"
2) "2"

Upvotes: 3

Related Questions