lua-users home
lua-l archive

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


In my lua 4.0 the following code crashes (with a floating point
exception):

a={}
a[2^31+1]=1

This is because the code in luaH_mainposition:

      h = (unsigned long)(long)nvalue(key);

performs an undefined conversion.  It is attempting to convert the
double that has value (2^31+1) to a long.  Converting from double
to long is only defined when the value of the integer part of the
number can be represented in the type long (see section 6.2.1.3 in
ISO 9899:1990).  2^31+1 is just outside the range that long can
represent on my platform (being a fairly ordinary 32 bit platform).
Converting from long to unsigned long is of course fine.

I think a proper fix to this slightly thorny because you'd like to be
able to do something like:

Number d = nvalue(key);
if(d < LONG_MAX + 1.0f && d > LONG_MIN - 1.0f) {
  h = (unsigned long)(long)d;
} else {
  h = 0;
}

but that assumes that the value LONG_MAX + 1 is in the range represented
by Number (double, say), and the same for LONG_MIN - 1.  Of course this
is true for any representation of float and double that I have seen.

And then there's the issue of changing Number to be long or int (in
which the original code is fine, and my suggested replacement is not).

luaH_getnum also needs fixing.


Cheers,
 drj