lua-users home
lua-l archive

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


On Tue, Jun 24, 2014 at 8:20 AM, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
> To be honest, we never thought much about that. Integers first entered
> Lua through the C API (lua_pushinteger, lua_tointeger), and we followed
> C in truncating floats when doing the conversion. (It was also cheaper,
> which was important because such conversions were quite common.) But
> the question is quite pertinent: is this useful at all? If a program
> specifices 3.2 as a character index in a string, is it useful to
> silently truncate that to 3? Or maybe it would be better to throw an
> error in that case?  In the rare cases that the programmer really wants
> to truncate, that probably should be done explicitly.

Yes, I would tend to think that explicit is better than implicit here.
Throwing an error feels like the right behavior to me.

The fact that C will implicitly convert double -> string is an
interesting perspective. But the static vs. dynamic typing seems to
change the situation somewhat. In C, the fact that a conversion is
occurring is a static and predictable property of the program. It's
also something the compiler can warn you about.

If I compile this with clang -Weverything:

void f(int x);
void g(float x) { f(x); }

I get the error message:

implicit conversion turns floating-point number into integer: 'float' to 'int'

In Lua with dynamic typing, the conversion happens silently, and is a
function of run-time data flow that is difficult to statically analyze
or predict. If my code was passing 3.2 as an character index in a
string, I think I'd want to know about it. It probably means I should
fix my program.

I would tend to think that integral-valued floats should be accepted
wherever integers are though.

Josh