as far as I know is better to use unidimensional table to implement multidimensional array (like in C). Here an example that should do the affair:
local function tmul(ls)
local p = 1
for i, v in ipairs(ls) do p = p*v end
return p
end
function init_multi_table()
local mt = {}
local default_value = 0
local get_index = function(argls)
local t = table.remove(argls, 1)
local dt = tmul(t.dims)
local index = 1
for i, d in ipairs(t.dims) do
dt = dt / d
index = index + dt * (argls[i] - 1)
end
return t, index
end
local get = function(...) local t, i = get_index(arg); return t[i] end
local set = function(...)
local v = table.remove(arg)
local t, i = get_index(arg)
t[i] = v
end
local function create(...)
local dt = tmul(arg)
local t = {}
setmetatable(t, mt)
mt.__index = mt
t.dims = arg
for i=1,dt do t[i] = default_value end
return t
end
mt.get = get
mt.set = set
mt.create = create
return mt
end
MultiTable = init_multi_table()
mytb = MultiTable.create(3,7,5) -- create a 3-dimensional array 3x7x5
mytb:set(2,5,1, 3.14)
x = mytb:get(2,5,1) -- 3.14
x = mytb:get(3,5,1) -- 0
Francesco