[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Recommended way of setting up multidimensional arrays
- From: Emmanuel Oga <emmanueloga@...>
- Date: Wed, 23 Feb 2011 21:04:34 -0300
Hi,
I came up with this code for setting up dynamic, multidimensional arrays:
local dynArray
local dynArrayMeta = {
__index = function(self, key)
local new = dynArray()
self[key] = new
return new
end
}
dynArray = function(initial)
return setmetatable(initial or {}, dynArrayMeta)
end
-- usage:
darr = dynArray()
specialKey = {}
for x = 1, 3 do
for y = 1, 3 do
for z = 1, 3 do
darr[specialKey][x][y][z] = x .. " " .. y .. " " .. z
end
end
end
for x = 1, 3 do
for y = 1, 3 do
for z = 1, 3 do
print(darr[specialKey][x][y][z])
end
end
end
Usage, I believe, is straightforward. But since I see the question
about multidimensional arrays coming up frequently, I'm wondering if
I'm missing something with this code (e.g. any
performance/memory-waste considerations, possibility of hidden errors
appearing, etc...).
For instance one thing that could be considered problematic is
assigning to a dimension smaller than the biggest one:
darr = dynArray()
darr[1][2] = 3 -- 2 dimensions
darr[1] = "oh-oh" -- assigning to the first one breaks stuff.
but I'm really not worried a lot about that one since I'm being
careful on how I use the array.
Greets.
--------------------------------------------------------------
EmmanuelOga.com - Software Developer