lua-users home
lua-l archive

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


Today, we converted a project from Lua v5.02 to v5.1.1, and we started having a problem when converting double to int. I have narrowed my problem down to code that has nothing to do with Lua. But I still wanted to get other people's opinions about it.

double d = 0xFFFFFFFF;
int n;
n = (int)d;

// n now contains 0x80000000

n = (int)(unsigned int)d;

// n now contains 0xFFFFFFFF

(this happens on both VS2005, and GCC 4.0.1 (Apple Computer, Inc. build 5363))

Since lua_number2int and lua_number2integer both basically do this: "n = (int)d;"

Wouldn't it be safer to do this: "n = (int)(unsigned int)d;" so as to preserve the values that would otherwise be truncated ?

What sort of problems would this cause?  Is my fix unportable?

The initial problem we got stems from doing this in Lua:

d = 0xFFFFFFFF
Foo(d)

// Assuming Foo() is something like this...

int bind_Foo(lua_State *L)
{
Foo(lua_tointeger(L, 1)); // value passed to Foo() is now truncated to 0x80000000

   return(0);
}

Brian