lua-users home
lua-l archive

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


Hi all,

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

2009/10/6 Michael Gerbracht <smartmails@arcor.de>
Hello Jerome,

In article <89d273ba0910060340q1b43e7e3y22afa986a4290557@mail.gmail.com">89d273ba0910060340q1b43e7e3y22afa986a4290557@mail.gmail.com>,
  Jerome Vuarand <jerome.vuarand@gmail.com> wrote:
> 2009/10/6 Michael Gerbracht <smartmails@arcor.de>:
> > I would like to create a multidimensional table with a lua fuction
> > containing a predefined value[1] instead of nil which should work like
> > this:

> You can do it recursively :

> function table.dim(size, ...)
>     assert(type(size)=='number')
>     local lastlevel = select('#', ...)==0
>     local t = {}
>     for i=1,size do
>         if lastlevel then
>             t[i] = 0
>         else
>             t[i] = table.dim(...)
>         end
>     end
>     return t
> end

Thank you very much, this looks much better!

Michael