[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Serialization of math.huge
- From: Rob Kendrick <rjek@...>
- Date: Tue, 29 May 2012 18:57:31 +0100
On Tue, May 29, 2012 at 10:03:16AM -0700, Paul K wrote:
> Hi All,
> 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).
How the C library converts inf to a string and back again is a shadowy
corner of the spec. Under glibc, this works fine, returning the string
> =tonumber "inf"
Similar problems will exist for NaN, I suspect.
The simple solution is to set up some variables containing inf, -inf,
nan, and -nan, and then use them to compare every number to check for
these special cases.
inf = 1/0
-inf = -1/0
Then, you can see if there's a math.huge to deal with by seeing if the
number equals inf (or math.huge, as it happens), and the opposite
problem with -inf (and encode it as -1/0).
NaN is a bit trickier: if a number is not equal to itself, then it is
NaN. You can encode this as 0/0. (ie: if foo ~= foo then ... end)