lua-users home
lua-l archive

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


For all the arithmetic operators(+/*-), if your inputs are integers, then your output must be an integer (unless you go outside the representable range).  The exception is division, so integer division handles that case.  So if you convert all your inputs to integers and use integer division instead of float division, you'll never have a non-integer.

On Wed, Oct 9, 2019, 11:44 AM Russell Haley <russ.haley@gmail.com> wrote:


On Wed, Oct 9, 2019 at 6:02 AM Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> Is there any way to enforce integer arithmetic in Lua 5.3
>
> e.g.
>
> x = 5 / 2 -- => 2
> where x is an integer?

1) Do not use '/' or '^'.

2) For any value that enters the computation that you cannot be sure
it is an integer, apply a conversion to it. How to convert depends
on you:

- x | 0   -- fast, raises an error if x is not an integer value

- math.tointeger(x)      -- returns falsy if x is not an integer value

- math.floor, math.ceil, math.modf
     -- rounds x (but the result may not be in the proper range)


-- Roberto

For my edification:  The answer is then "No, there is no way 'in general' to perform integer math"? It seems to me that all the suggestions above are value conversions/coercion and have nothing to do with actually performing the integer math equation requested by the OP?