Lua cJSON number format

582 views
Skip to first unread message

knac...@googlemail.com

unread,
Jan 20, 2015, 1:56:52 AM1/20/15
to redi...@googlegroups.com
Hi everybody,

I'm doing my first steps scripting with lua. CJSON seem to convert all numbers to integers. I expect the following to be converted to a float.

test2.json:
{
"float": 1.2
}

test.lua:
local log = {}

local function append_to_log(log, msg)
  log
[#log +1] = msg
end

local function read_json(json)
 
local data = cjson.decode(json)
 
for k, v in pairs(data) do
    append_to_log
(log, k)
    append_to_log
(log, v)
 
end
end

append_to_log
(log, "Ask Lua what type 1.2 is ...")
append_to_log
(log, type(1.2))

read_json
(ARGV[1])

return log

leads to:
[jan@localhost lua]$ ~/redis/redis-2.8.19/src/redis-cli eval "$(cat test.lua)" 0 "$(cat test2.json)"
1) "Ask Lua what type 1.2 is ..."
2) "number"
3) "float"
4) (integer) 1

Do I misunderstand something about Lua, Redis, cJSON and number conversions or might there be another issue (bug?)?

Thanks and best regards,

Jan

Josiah Carlson

unread,
Jan 20, 2015, 2:21:43 AM1/20/15
to redi...@googlegroups.com
You misunderstand something about Lua. Unless compiled otherwise, the "number" type is a double, and your output is printing out:

1) "Ask Lua what type 1.2 is ..." -- the literal string you told it to
2) "number" -- the type of the decoded 1.2
3) "float" -- the attribute name
4) (integer) 1 -- the attribute value, converted to a "proper" output format

Note that when Redis returns data from a Lua script (or sends it to the log), part of the process converts numbers to their integer equivalent. So in this case it's not that the cjson library is broken, it is that the way Redis converts numbers from Lua to the caller and to the log is not precise.

127.0.0.1:6379> eval "return cjson.decode(ARGV[1])['float'] * 5" 0 '{"float":1.2}'
(integer) 6
127.0.0.1:6379> eval "return cjson.decode(ARGV[1])['float'] * 3" 0 '{"float":1.2}'
(integer) 3
127.0.0.1:6379> eval "return 1.4" 0
(integer) 1

This is documented under the section entitled "Conversion between Lua and Redis data types" on http://redis.io/commands/eval .


When I need to transfer information between Redis and Lua and clients anything beyond a string or integer, I always try to explicitly encode my data (to json or similar).

 - Josiah


--
You received this message because you are subscribed to the Google Groups "Redis DB" group.
To unsubscribe from this group and stop receiving emails from it, send an email to redis-db+u...@googlegroups.com.
To post to this group, send email to redi...@googlegroups.com.
Visit this group at http://groups.google.com/group/redis-db.
For more options, visit https://groups.google.com/d/optout.

knac...@googlemail.com

unread,
Jan 20, 2015, 3:13:11 AM1/20/15
to redi...@googlegroups.com
I see. Thanks very much!
Reply all
Reply to author
Forward
0 new messages