English 2D arrays in Lua?

4 replies
Goto Page
To the start Previous 1 Next To the start
25.02.11 03:01:58 pm
Up
DannyDeth
User
Offline Off
Hi all,

I am busy doing a small Lua project which involves an array containing the entire map on an array, and because I cannot use a 1D array to do this, I need to know how I could create a 2D array if it is possible to do so.

EDIT: I think it might be something like this but I am not sure:
Code:
1
array2d = {}{}


Thanks,
DannyDeth.
25.02.11 03:18:52 pm
Up
Roni
User
Offline Off
array2d=
{
     {}
}

or jsut array2d={{}}
25.02.11 03:19:43 pm
Up
Banaan
User
Offline Off
You need tilex by tiley right?

Code:
1
2
3
4
array2d = {
     x = {},
     y = {}
}


for tile 3|2 you simply use
Code:
1
x, y = array2d.x[3], array2d.y[2]

Or isn't that what you're looking for?
25.02.11 03:20:04 pm
Up
Flacko
User
Offline Off
Well, since a 2D array is an array (or a group of them) inside another array:
Code:
1
array2d = {{}}


BTW, here's a function similar to lee's initArray that will create an array of an arbitrary number of dimensions:
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function table.copy(t)
     local b = {}
     for k,v in pairs(t) do
          if type(v)=='table' then
               v = table.copy(v)
          end
          b[k] = v
     end
     return b
end

function table.array(v, ...)
     local t = {}
     if arg[2] then
          v = table.array(v,table.unpack(arg,2))
     end
     for i=1,arg[1] do
          if arg[2] then v = table.copy(v) end
          t[i]=v
     end
     return t
end


usage:
Code:
1
a = table.array(5,32,32) --32x32 array filled with 5s


Edit: Whoops, didn't read you were storing a map. If that's the case, it's still possible to store a whole map in a 1D array, you just need to know what's the width of the map:
Code:
1
oned[y*width+x] = twod[x][y]

(Assuming you're storing the map "line-by-line")
edited 1×, last 04.08.11 09:54:06 pm
25.02.11 03:30:14 pm
Up
DannyDeth
User
Offline Off
Ok, thanks you guys
I tried searching for info but it was all about sparsing which just isn't my scene, I've used it before and it isn't nice ( considering it can take like 200mb of RAM, it sux ).

@Banaan: No it isn't exatly what I wanted but... yeah. It it kinda usable. To a degree.

Flacko's was slightly more usable, thanks to all anyway.

~Danny
To the start Previous 1 Next To the start