lua-users home
lua-l archive

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


Hi,

Mike's scimark.lua contains a trick that makes working with the FFI arrays in Luajit and with tables in vanilla Lua almost seamless.

However, FFI arrays are zero-based, and Lua tables are one-based.  Here's a modified version of Mike's array_init() and an illustration of the problem:

local darray

local function array_init()
 if jit and jit.status and jit.status() then
   local ok, ffi = pcall(require, "ffi")
   if ok then
     darray = ffi.typeof("double[?]")
     return
   end
 end
 darray = function(n, ...)
   local a = {}
   for i = 1, select('#', ...) do a[i] = select(i, ...) end
   return a
 end
end

array_init()

a = darray(3, 1, 2, 3)

print(a[0], a[1], a[2], a[3])

Output with Lua is: nil	1	2	3
and with LuaJIT: 1	2	3	4.268776586633e-319

What's best practice for working around this?  I could change the vanilla darray to

 darray = function(n, skip, ...)
   local a = {}
   for i = 1, select('#', ...) do a[i] = select(i, ...) end
   return a
 end

and always initialise arrays with an extra initial element.  array_init could set an OFFSET variable that I could use in loop counters?

Anyone got any better ideas?

Cheers,
Geoff