Forum

> > CS2D > Scripts > 2D arrays in Lua?
Forums overviewCS2D overview Scripts overviewLog in to reply

English 2D arrays in Lua?

4 replies
To the start Previous 1 Next To the start

old 2D arrays in Lua?

DannyDeth
User Off Offline

Quote
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:
1
array2d = {}{}

Thanks,
DannyDeth.

old Re: 2D arrays in Lua?

Banaan
User Off Offline

Quote
You need tilex by tiley right?

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

for tile 3|2 you simply use
1
x, y = array2d.x[3], array2d.y[2]
Or isn't that what you're looking for?

old Re: 2D arrays in Lua?

Flacko
User Off Offline

Quote
Well, since a 2D array is an array (or a group of them) inside another array:
1
array2d = {{}}

BTW, here's a function similar to lee's initArray that will create an array of an arbitrary number of dimensions:
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:
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:
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

old Re: 2D arrays in Lua?

DannyDeth
User Off Offline

Quote
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
Log in to reply Scripts overviewCS2D overviewForums overview