Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What is the best way to create a 2D array in Roblox?

I'm trying to create a 9 by 5 board to replicate a game I play with a friend, DigitalVeer, called Fanorona.

He showed me a way that we can make a 2D matrix as the following:

grid = { };

function newPoint(x, y)
if not grid[y] then
grid[y] = { }
end
grid[y][x] = {x = x; y = y; vector = Vector2.new(x, y)}
end

for y = 1, 5 do
for x = 1, 9 do
newPoint(x, y)
end
end

What are some other ways for creating a 2D matrix in a way good for dealing with things such as boards where I also need to store values inside the arrays?

1 answer

✓ Accepted answer

The way you're doing it is the only way to create 2D arrays in Lua: using Tables.

What you put in those Tables (line 7 in your code) is how you add more data to the specific tile in question.


Additionally, it's a good idea to format your code for readability;

grid = { };

function newPoint(x, y)
	if not grid[y] then
		grid[y] = { }
	end
	grid[y][x] = {x = x; y = y; vector = Vector2.new(x, y), someValue = true, tileValue = 25}
end

for y = 1, 5 do
	for x = 1, 9 do
		newPoint(x, y)
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.