lua-users home
lua-l archive

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


How about this workaround (ugly, but still could work):

local ffi = require( "ffi" )

ffi.cdef[[
   typedef struct vec3 {
     float x, y, z;
   } vec3;
]]

local a = ffi.new( "vec3[?]", 1024 + 1 )
local b = ffi.cast( "vec3*", ffi.cast("size_t", a) - ffi.sizeof("vec3"))

print(a)
print(b)

for k = 1, 30 do
   b[k].x = k
end

for k = 0, 29 do
   print( a[k].x )
end

The trick here is that 'a' has to be kept, so that 'b' would work (not sure, Mike would know better)

	
On 6/13/2012 4:07 PM, Chris wrote:
On Wed, Jun 13, 2012 at 6:52 PM, Dimiter 'malkia' Stanev
<malkia@gmail.com>  wrote:
LuaJIT FFI handles "C" types, and in "C" arrays start from 0.

The solution is to let your users be aware of this from the start.
No better solution than this.

It's much more complicated than that.  Often it's hard to tell what is
FFI and what is regular Lua.  There is not always a clear separation
because usually a combination of FFI and Lua types are used all at
once.  I run in to this a lot when managing multiple FFI types in a
regular Lua table and I often introduce bugs because of it (and I
supposedly know what I am doing; no hope for a regular user).

Unfortunately there doesn't seem to be a clean solution because even
changing LuaJIT to use one-based indexing will have problems with
pointer arithmetic and such.

Honestly I think a top to bottom reworking of Lua to use zero-based
indexes is the only clean solution.  That's not so easy, especially if
doing it in the LuaJIT codebase because every library needs to switch
to the zero-based mechanism (even the stack, etc; everything would
have to change).

CR