lua-users home
lua-l archive

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

On 15 Nov 2006, at 00:39, David Given wrote:

Brian Weed wrote:
So, to be safe, maybe I should do this?

#define lua_number2integer(i, d) ((d) < 0 ? (i) = (int)(d) : (i) =
(int)(unsigned int)(d))

Actually, I think the only way to be completely safe would be to do:

int lua_number2integer_f(double d)
	if (d < INT_MIN)
		return INT_MIN;
	if (d > INT_MAX)
		return INT_MAX;
	return (int)d;

#define lua_number2integer(i, d) i=lua_number2integer_f(d)

...but that's rather a mouthful, and of course you'd need a completely
separate version for unsigned ints.

I think you're right; this is the only safe way. I'm amazed that this has gone unnoticed. Of course, even with this solution it's _possible_ to construct a perverse C implementation where it would be undefined behavious (if INT_MAX was huge enough to be outside the range of double).