lua-users home
lua-l archive

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


Hi, I'm new to the list and have a question which I've tried researching about in the archives, but not found a conclusive answer for there:

Why does lua cast floating point values to integers without first checking the validity of the cast by checking that the float is within the int's range of representation? Isn't doing so undefined behavior (see e.g. http://stackoverflow.com/questions/3986795/casting-float-inf-to-integer)?

See http://lua.2524044.n2.nabble.com/FPE-with-using-gt-INT-MAX-numbers-in-Lua-td4985976.html for lua 5.1.2 where I also encountered the same problem, but also lua 5.2 seems to have this issue by looking at the source code:
http://www.lua.org/source/5.2/ltable.c.html, e.g. in 

/*
** returns the index for `key' if `key' is an appropriate key to live in
** the array part of the table, -1 otherwise.
*/
static int arrayindex (const TValue *key) {
  if (ttisnumber(key)) {
    lua_Number n = nvalue(key);
    int k;
    lua_number2int(k, n);
    if (luai_numeq(cast_num(k), n))
      return k;
  }
  return -1;  /* `key' did not match some condition */
}

Before calling lua_number2int here, should not the size of n be checked, e.g. via 
if (n >= INT_MIN && n <= INT_MAX) {...}?

I understand that having an extra branch here will slow down number handling, but without doing so, this function as well as luaH_get lead to floating point exceptions when they are turned on, and to undefined behavior when they are turned off - both not very desirable.

An easy test case is lua statement
local e = 1.0e10

Best regards,

Michael Brandl