How to convert 1D array to multi dimensional matrix?

I am attempting to create my own encryption method for an exercise in LUA, but I don’t seem to be converting my array correctly. I am wondering if I am doing this incorrectly, but I am trying to create a function that will take an array, and convert it into a matrix, example here:

-- Give function input of
Table = {1,2,3,4,5,6,8,8}

-- Return output of 
Matrix = {{1,2,3,4},
          {5,6,7,8}}

Here is my current code that I attempted to use:


Table = {1,2,3,4,5,6,7,8}

-- Matrix Functions

local function SetMatrix(Rows, Cols, Table)
	local Matrix = {}
	for i = 1, Rows do
		for j = 1, Cols do
			Matrix[i][j] = Table[(i-1)*Cols + j]
		end
	end
	return Matrix
end

print(SetMatrix(2,4,Table))

When calling the function, I get this error:
image

1 Like

The reason for your error is because Matrix[i] is nil when you try to assign to Matrix[i][j].
A simple fix would be to assign Matrix[i] an empty table before the inner-loop.

1 Like

Ah yes, that worked, thank you for clearing that up.

1 Like