lua-users home
lua-l archive

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


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.