lua-users home
lua-l archive

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


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:
>
> example = table.dim(10,10,10)
> print(example[2][4][3])
>
> output --> 0
>
> My problem is that the table may have n dimensions. I tried to program this
> in lua:
>
> do
>
> function table.dim(...)
>  local d = {...}
>  result = {}
>  local function adddim(res,dim)
>    dim = dim or 1
>    if dim == #d then
>      for i = 1,d[dim] do
>        loadstring(res.."["..i.."] = 0")()
>      end
>    else
>      for i = 1,d[dim] do
>        loadstring(res.."["..i.."] = {}")()
>        adddim(res.."["..i.."]",dim+1)
>      end
>    end
>  end -- function
>  adddim("result")
>  return result
> end
>
> local example = table.dim(10,10,10)
> print(example[2][4][3])
>
> end
>
> I do not like that the table "result" is a global table. Is there a more
> clever way to do what I want?
>
> Thank you very much!
> Michael
>
> [1] I know that you can change the default value using metatables. But in
> this case it is important that the multidimensional table is created.

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