Re: Unexpected type conversion for arithmetic with cdata<double &>

  • From: Mike Pall <mike-1410@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Thu, 16 Oct 2014 20:49:10 +0200

Simon Cooke wrote:
> In the following test, arithmetic with cdata<double &> forces
> conversion to 64-bit integers:

All types of cdata numbers use 64 bit integer arithmetic (that's
in the docs).

And in this case you get a cdata double because you explicitly
force it with a reference. If you directly load v[0], then you get
a plain Lua number, which in turn would use FP arithmetic.

In other words: don't explicitly create stand-alone scalar cdata
types, e.g. ffi.new("int") (<-- BAD IDEA) or via scalar references.
They are rarely useful.

The only exception are 64 bit integers, which are always scalar
cdata objects. But these are implicitly created most of the time,
anyway (64 bit field/element acesses, 1LL or 1ULL literals).

[The regular C coercion rules wouldn't make sense in the context
of the FFI, since Lua numbers are doubles and would always have
the highest rank: x+1 would always give a double, even if x is a
64 bit integer. That's why cdata arithmetic uses "sticky" 64 bit
arithmetic throughout.]

--Mike

Other related posts: