[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua 5.3: How to get integer from out of range float?
- From: Roberto Ierusalimschy <roberto@...>
- Date: Wed, 6 Aug 2014 14:31:46 -0300
> Using 5.3 with #define LUA_INT_INT:
>
> return math.pow(2,31)>>0
> stdin:1: number has no integer representation
> stack traceback:
> stdin:1: in main chunk
> [C]: in ?
>
> To get integer anyway, with wraparound as it should be, ie equivalent of
> int32_t i = (int64_t)d in C, one can:
>
> string.format("%.0f", math.pow(2,31))>>0
> -2147483648
>
> This gives the correct result, but feels somewhat kludgy taking the detour
> via string. Does anyone know of a better way?
I guess this does what you want:
-- convert a float to a 32-bit integer, doing wrap around
function int (x)
local x = math.floor(x) -- or ceil or modf or some other rounding
x = (x + 2^31) % 2^32 - 2^31
return math.tointeger(x)
end
-- Roberto