Creating a 2-dimensional array via FFI

  • From: Shmuel Zeigerman <shmuz@xxxxxxxxxx>
  • To: LuaJIT list <luajit@xxxxxxxxxxxxx>
  • Date: Fri, 25 Jun 2021 11:32:53 +0300

Hello,

What is a proper way of creating a 2-dimensional array where the dimensions may vary?
The array should not be built with Lua tables.
The array must be accessed as usual, i.e. arr[m][n] must be legal syntax.
I wrote the function below but with a feeling there must be a better way to do that
(mostly because of my poor FFI knowledge).
Thank you.


local ffi = require "ffi"

local function board(height, width)
  _G.chess_board_type = (_G.chess_board_type or 0) + 1 -- use a global to withstand reloading macros
  local strtype = "chessboard" .. _G.chess_board_type
  ffi.cdef(("typedef int8_t %s[%d][%d];"):format(strtype,height,width))
  local brd = ffi.new(strtype)
  ffi.fill(brd, height*width, -1)
  return brd
end

--
Shmuel


Other related posts: