lua-users home
lua-l archive

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


I think that Roberto first specified (if I remember well, sorry otherwise) that float and integers are subtypes, that would be transparent for the user. My interpretation is that both subtypes can be used together without such problems, with a transparent conversion. Also the // operator was presented as a division giving integer results, whatever are the operands, and could be used for the conversion from float to integer in the specific case presented in the email.
Just to say that I was not expecting that behaviour, as the integer/float mechanism is not as transparent as it should be. Care must be taken to the operations to not get a unexpected error.

Alexandre

--- Original Message ---

From: "Dirk Laurie" <dirk.laurie@gmail.com>
Sent: 16 November 2014 20:02
To: "Lua mailing list" <lua-l@lists.lua.org>
Subject: Re: [5.3] Converting a floating point number to integer.

2014-11-16 15:09 GMT+02:00 Liam Devine <liamdevine@oolua.org>:
> I am trying to convert a floating point number to an int and the beta
> release seems to have added some more restrictions on the conversions.

The documentation is unambiguous on this point.

| The conversion from float to integer checks whether the float has an exact
| representation as an integer (that is, the float has an integral
value and it is
| in the range of integer representation). If it does, that
representation is the
| result. Otherwise, the conversion fails.

> What is the current recommended method of converting a float to int?
> Should it be to check if it is greater than zero and floor else use
> ceiling and then finally use one of the above conversion methods?

Converting a float with a non-zero fraction part to an integer
is application-dependent. The user must decide what is correct
for his application: floor, ceil, closest (coded e.g. as floor(x+0.5)),
truncate (as you suggest) or error. The current default of `nil` in
effect opts for error, except that the error is only signalled later.

> If this behaviour is to stay, would it be time to have a cast operator
> int() ?

You mean, Lua should pre-choose among the four options above
and elevate that from plausible to preferred?