lua-users home
lua-l archive

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


Getting back to the original question, this seems to work on
i386/linux and avr32/embedded newlib. Can people test on other
platforms?

-- version of tostring that serialises inf, -inf and nan in a way that
-- will allow you to read them back in again.
do
  local _tostring = tostring
  function tostring(x)
    if type(x) ~= "number" then
      return _tostring(x)
    end
    -- Trap special cases inf, -inf and nan
    if x == 1/0 then return "(1/0)" end      -- inf
    if x == -1/0 then return "(-1/0)" end    -- -inf
    if x ~= x then return "(0/0)" end        -- nan
    return(_tostring(x))                     -- other
  end
end

-- Make sure everything prints the same when converted to string and back
function test()
  local s = { -1, 0, 1, 1e-16, 1e16, 1/0, -1/0, 0/0 }
  local before, after = "", ""
  -- save initial string values
  for _,v in ipairs(s) do
    before = before .. tostring(v)
  end
  -- convert there and back again
  for i,v in ipairs(s) do
    s[i] = assert(loadstring("return " .. tostring(v)))()
  end
  -- see what the result is
  for _,v in ipairs(s) do
    after = after .. tostring(v)
  end
  if before == after then
    print "PASS"
  else
    print("Before: "..before)
    print("After : "..after)
  end
end

test()