ServiceStack Redis, how to return Lua table as List

佐手、 提交于 2019-12-03 15:30:26
Tw Bert

From Lua, you need to return a Lua Array, or a JSON object. 'myTable' sounds like a handle that is only valid inside the Lua interpreter. That handle is cleaned up directly after the call, so won't get propagated to the client.

Edit: a simple Lua Table/Array should be supported. Not sure what's going on then, without looking at the script.

See also this SO link for some extra info about atomicity of Lua scripts.

Hope this helps, TW

After edit OP:

This was the OP's original Lua script:

local a={}
for i = 1, 1, 1 do
  a["47700415"] = redis.call('hget', 'asr:47700415', 'MDEngines')
  a["47700415_000"] = redis.call('hget', 'asr:47700415_000', 'MGEngines')
end
return a

Answer: You can't return nested values in the Lua return value. As you can see from your ServiceStack function, a Lua script returns a list, and a list is not nested.

Here are two solutions, the one with JSON gives slight overhead (but might be easier when programming, and is nill-safe).

a: Using cjson

local a={}
for i = 1, 1, 1 do
  a["47700415"] = redis.call('hget', 'asr:47700415', 'MDEngines')
  a["47700415_000"] = redis.call('hget', 'asr:47700415_000', 'MGEngines')
end
return cjson.encode(a)

MsgPack is also a very nice and compact serialization format (we use it a lot), and can be returned like this:

a-alt: Using cmsgpack

return cmsgpack.pack(a)

b: Using a simple array

local a={}
for i = 1, 1, 1 do
  a[1] = "47700415"
  a[2] = redis.call('hget', 'asr:47700415', 'MDEngines')
  a[3] = "47700415_000"
  a[4] = redis.call('hget', 'asr:47700415_000', 'MGEngines')
end
return a

This returns:

a:

tw@srv-flux-02:~$ redis-cli -p 14312 EVAL "$(cat ~/tw_luatest.lua)" 0 0
"{\"47700415\":\"Hello\",\"47700415_000\":\"World\"}"

b:

tw@srv-flux-02:~$ redis-cli -p 14312 EVAL "$(cat ~/tw_luatest2.lua)" 0 0
1) "47700415"
2) "Hello"
3) "47700415_000"
4) "World"

As you can see, I put some dummy data in the HSET.

I can also recommend this link, some nice info in there: intro-to-lua-for-redis-programmers

A nice way of adding values to a Lua dict can be seen here :

local fkeys = redis.call('sinter', unpack(KEYS))
local r = {}
for i, key in ipairs(fkeys) do
  r[#r+1] = redis.call('hgetall',key)
end
return r
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!