Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

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

Asked by 9 years ago

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

Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

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
Ad

Answer this question