Help with matrices

Hello, i want to know what’s wrong in my code? :frowning:

-- Create a new table
mat = {}

-- Loop all matrix values
for i = 1, N do
  mat[i] = {} -- Create a new row
  for j = 1, M do
    mat[i][j] = 0
  end
end

-- N = is the number of rows
-- M = is the number of columns
-- i = is used to keep track of row indexes
-- j = is used to keep track of col indexes

I don’t see anything wrong.

Moreover it’s the exact same as this stack overflow question on making a 2D array in lua with a lot of upvotes so it should be even more ok.

Edit: Oh yeah I assumed the numbers for rows and columns were already defined but yeah make sure to do what @NexusValiant said.

Otherwise I recommend searching online and comparing code samples if you know what the programming term is called though we can help you with that.

You’re attempting to use the N and M variable when you didn’t define it. Here’s a fix.

N = 5 -- change number to change the number of rows
M = 5 -- change number to change the number of columns
mat = {}
for i = 1, N do
  mat[i] = {} 
  for j = 1, M do
    mat[i][j] = 0
  end
end
2 Likes