Discussion:
Unexpected type conversion for arithmetic with cdata<double &>
Simon Cooke
2014-10-16 15:24:33 UTC
Permalink
In the following test, arithmetic with cdata<double &> forces
conversion to 64-bit integers:
--------------------
local ffi = require'ffi'
local v = ffi.new('double[1]',2.5)
local x = ffi.cast('double&',v)

print(x, tonumber(x))
print(x+.25, tonumber(x)+.25)
print(x-.25, tonumber(x)-.25)
print(x*.25, tonumber(x)*.25)
print(x+x, tonumber(x)+tonumber(x))
--------------------
cdata<double &>: 0x01fbb9f8 2.5
2LL 2.75
2LL 2.25
0LL 0.625
4LL 5

(Tested using both LuaJIT 2.0.3 and the latest 2.0 HEAD, on 64 bit
GCC-4.9 and MSVC-12)
From the manual I would expect conversion to 'number'. Is this a bug?
Simon
Mike Pall
2014-10-16 18:49:10 UTC
Permalink
Post by Simon Cooke
In the following test, arithmetic with cdata<double &> forces
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
Simon Cooke
2014-10-16 19:20:24 UTC
Permalink
This was a contrived example to create the reference type. My issue
involved an FFI function that indexed an element of an array stored
inside a C++ object and returned a reference to it. From the docs I
took "Reference types are dereferenced before a conversion can take
place" to mean that it would convert to double automatically when
used, but now I see that this doesn't apply here. I can modify the
return type of the function to return by value for scalar types.
Thanks for the clarification.

Simon
null
2014-10-20 01:50:38 UTC
Permalink
if not , is there any plan to support it ?
Mike Pall
2014-10-20 22:26:36 UTC
Permalink
Post by null
if not , is there any plan to support it ?
Not at this time. It's not so easy, see:

http://www.freelists.org/post/luajit/luajit-porting-to-wp8-arm-version,1

--Mike

Loading...