lua-users home
lua-l archive

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


On Wednesday 23 February 2011 19:04:34 Emmanuel Oga wrote:
> 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...).

I've only done Lua for a couple months, so consider the source and ask other 
opinions. That said, I'll give you my opinion.

In my opinion, multidimensional arrays are determined exclusively by the 
problem domain. In other words, do you want a list of data rows containing 
data columns, like an in-memory version of a database table? Do you want an 
in-memory version of a linear index file, which would be a numeric array of 
value->key pairs? Do you want a list of years, each containing a list of 
months, each containing a list of days, each containing a dayname?

Do you want some sort of tree structure? A linked list? A data device which in 
C would be a struct, or a struct containing structs containing structs? It's 
all easily doable with tables.

I'm thinking once you know what you really want, you know what it should look 
like and how to construct it. Personally, and this is just speaking for 
myself, I wouldn't try to built a one-size-fits-all tool for a 
multidimensional array -- I'd let the problem domain define it, and spend 
fifteen minutes or an hour "reinventing the wheel" rather than take time to 
use and debug a somewhat complex "one-size-fits-all" tool.

SteveT

Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt