lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, May 29, 2012 at 9:03 PM, Paul K <paulclinger@yahoo.com> wrote:
> I've been working on a simple serialization module (yes, I carefully
> reviewed the implementations listed here
> http://lua-users.org/wiki/TableSerialization) and came across an issue
> with math.huge. tostring(math.huge) returns "1.#INF", but this value
> isn't interpreted as a valid number (when I'm loading the generated
> string with loadstring). It seems like these values (+/-math.huge)
> need to be treated as special cases, but I don't see this logic in any
> of the modules I reviewed (including those that aim to provide a
> complete serialization solution).
>
> A simple test using serialize.lua from metalua:
>
> require "serialize"
> local s = serialize {[math.huge] = -math.huge}
> local _, err = loadstring(s)
> print(s, err)
>
> This outputs:
>
> return { [1.#INF] = -1.#INF }   [string "return { [1.#INF] = -1.#INF
> }"]:1: ']' expected near '#'
>
> Does this indeed need to be handled as a special case, or am I missing
> some simple solution?

This is handled in latest lua-nucleo[1] tstr()[2], tserialize()[3] and
tpretty()[4].

The code to handle the case[5]:

-- convert numbers into loadable string, including inf, -inf and nan
local serialize_number
do
  local t =
  {
    [tostring(1/0)] = "1/0";
    [tostring(-1/0)] = "-1/0";
    [tostring(0/0)] = "0/0";
  }
  serialize_number = function(number)
    -- no argument checking - called very often
    local text = ("%.17g"):format(number)
    -- on the same platform tostring() and string.format()
    -- return the same results for 1/0, -1/0, 0/0
    -- so we don't need separate substitution table
    return t[text] or text
  end
end

HTH,
Alexander.

[1] https://github.com/lua-nucleo/lua-nucleo/
[2] https://github.com/lua-nucleo/lua-nucleo/blob/master/lua-nucleo/tstr.lua
[3] https://github.com/lua-nucleo/lua-nucleo/blob/master/lua-nucleo/tserialize.lua
[4] https://github.com/lua-nucleo/lua-nucleo/blob/master/lua-nucleo/tpretty.lua
[5] https://github.com/lua-nucleo/lua-nucleo/blob/master/lua-nucleo/string.lua#L321-344