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.

- Because this conversion is quite frequent in Lua and we tried to make
it fast.

- Because it is hard to find a machine where this undefined behavior
results in something nasty (like a crash).

- Because the resulting value in that case is usually irrelevant.

Note that the code uses an "external" macro to do this conversion, so it
is easy to change it if you really need to.

In most machines (IEEE doubles and 32-bit lua_Integer), Lua uses a
"dirty trick" to do this conversion that is fast and does not have
undefined behavior in case of overflows (although it can give useless

Anyway, this mess is one of the motivations (a small one) for the
introduction of integers in Lua. (Having integers as a native
representation for numbers should greatly reduce the frequency of these
conversions, and therefore they could take the time to check the validity
of the cast before doing it.)

-- Roberto