Page 1 of 1

How to move one row of a grid?

Posted: Mon Jul 08, 2019 4:46 pm
by ITISTHEBKID
I have every cell of a grid in a table. How would I go about shifting all the cells over and moving the last row to the first row?

Re: How to move one row of a grid?

Posted: Tue Jul 09, 2019 2:17 pm
by pgimeno
It depends. If the purpose is something similar to Netslide, then you would go column by column, and for each column, set a variable to the element in the last row, then loop from the end backwards, setting each element to the previous (you would loop up to 2). Finally, you would set element 1 to the variable you stored.

In code:

Code: Select all

local grid = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
}

local numColumns = 3
local numRows = 3

for column = 1, numColumns do
  local wrappedElement = grid[numRows][column]
  for row = numRows, 2, -1 do
    grid[row][column] = grid[row - 1][column]
  end
  grid[1][column] = wrappedElement
end

for i = 1, numRows do print(unpack(grid[i])) end
--[[
 output:
7	8	9
1	2	3
4	5	6
--]]
For other purposes, you can get away with just using the % operator on the coordinates plus the offsets, but it's hard to give specific advice without more details.